1

I have a string:

string s = "1/09/2017 12:00:00 AM"; 

Output I want to show is 1/09/17 (basically short date).

And if

string s ="30/09/2017 12:00:00 AM"

Output I want to show is 30/09/17 (basically short date).

What I have tried is:

string[] values = s.Split('/');
string a = values[0]+"/"+values[1]+"/"+values[2].

I am confused how to get the 3rd part need help.

1
  • 3
    s.Split(" ")[0] Commented Nov 29, 2017 at 6:25

5 Answers 5

6

Use .NET built-in DateTime parsing.

For example:

string s = "1/09/2017 12:00:00 AM";
string format = "d/MM/yyyy hh:mm:ss tt";
DateTime parsedDateTime = DateTime.ParseExact(s, format, null);
string output = parsedDateTime.ToString("d/MM/yy"); //output = 1/09/17

More info:

2
  • This doesn't give the answer that the OP wants. Commented Nov 29, 2017 at 6:29
  • Op wants a two digit year as output
    – CSharpie
    Commented Nov 29, 2017 at 6:30
0

My suggestion would be to use the inbuilt date datatype. If that doesn't go with your requirement then I would suggest you to split the string based on the delimiter " "(blank space). Then pick the first part and proceed with your code.

0

You could use a substring like this

string s = "30/09/2017 12:00:00 AM";

        string[] values = s.Split('/');
        string a = values[0] + "/" + values[1] + "/" + values[2].Substring(2,2);
1
  • 2
    .Substring(2,3) should be .Substring(2,2). Commented Nov 29, 2017 at 6:27
0

Adding to Paolo's anwer

            string s = "1/09/2017 12:00:00 AM";
            string format = "d/MM/yyyy hh:mm:ss tt";
            DateTime parsedDateTime = DateTime.ParseExact(s, format, null);
            string output = parsedDateTime.ToString("d/MM/yy");
            string ss = output.Replace("-","/");
            Console.Write(ss); //output is 1/09/17

This will exactly return the exact expected output

0
DateTime date = DateTime.ParseExact("1/09/2017 12:00:00 AM", "d/MM/yyyy hh:mm:ss tt", null);
Console.WriteLine(date.ToString("d/MM/yy"));

Convert your date string to DateTime and then use ToString overloaded method method with parameter Format Please find Fiddle

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.