Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert "M/d/yyyy h:mm:ss tt" to "YYYY-MM-DDThh:mm:ss.SSSZ"

As title suggests, what I want to do is to convert my date-string e.g.

  • "6/6/2014 12:24:30 PM" (M/d/yyyy h:mm:ss tt) format

to

  • "YYYY-MM-DDThh:mm:ss.SSSZ" format.

I am trying in the following way. It's not giving me any exception, but I am getting the value like :

  • "YYYY-06-DDT12:24:30.SSSZ"

How can I exactly achieve this?

string LastSyncDateTime = "6/6/2014 12:24:30 PM";
DateTime dt = DateTime.ParseExact(LastSyncDateTime, "M/d/yyyy h:mm:ss tt",CultureInfo.InvariantCulture);
string result = dt.ToString("YYYY-MM-DDThh:mm:ss.SSSZ");
like image 645
YuDroid Avatar asked Dec 26 '14 10:12

YuDroid


People also ask

What is SSSZ in date format?

Dates are formatted using the following format: "yyyy-MM-dd'T'hh:mm:ss'Z'" if in UTC or "yyyy-MM-dd'T'hh:mm:ss[+|-]hh:mm" otherwise. On the contrary to the time zone, by default the number of milliseconds is not displayed. However, when displayed, the format is: "yyyy-MM-dd'T'hh:mm:ss.


2 Answers

Data time Formats Can't recognize, the non Case sensitive chars in some systems due to their internal settings. Please refer the below code, which works fine

string result = dt.ToString("yyyy-MM-ddThh:mm:ss.SSSZ");

The above code will result as 2014-06-06T12:24:30.SSSZ

EDIT :

The below snippet will give you milliseconds as well

dt.ToString("yyyy-MM-ddThh:mm:ss.fffZ");
like image 72
Sai Kalyan Kumar Akshinthala Avatar answered Sep 30 '22 11:09

Sai Kalyan Kumar Akshinthala


The simplest way is to use the "o" date formatter, like this:

dt.ToString("o");

This method will give you a timestring in the ISO 8601 format, something like this:

2014-12-25T11:56:54.9571247Z

but, since that ISO 8601 uses more than 3 decimal digits to define the second, if you only want to stop at milliseconds you can use the full formatting string and write down ss.fffzzz at the end, like this:

dt.ToString("yyyy-MM-ddThh:mm:ss.fffzzz");

and the result will be:

2014-12-25T11:56:54.957Z

For more informations you can refer to THIS LIST of date formatting options.

like image 26
Marco Bonelli Avatar answered Sep 30 '22 10:09

Marco Bonelli