Convert DateTime to specific format

What is the best and fastest way to convert DateTime to this format?

2015-03-26T18: 02: 58.145798Z

I am currently getting the date from the server and I can parse it and convert the date to DateTime and the output of ToString () looks something like this:

26/03/2015 18:02:58

For date conversion, I use this line of code:

var parsedDate = DateTime.Parse("2015-03-26T18:02:58.145798Z", CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);

      

What is the best way to convert parsedDate back to original format?

EDIT: I want to convert DateTime to this format 2015-03-26T18: 02: 58.145798Z as a string

+3


source to share


2 answers


If you have an object DateTime

, you can convert it to a string with a specific format using O

the format specifier:

parsedDate.ToString("O")

      

or

parsedDate.ToUniversalTime().ToString("O") // if parsedDate is not UTC

      



returns "2015-03-26T18:02:58.1457980Z"

.


If DateTimeKind

your object is DateTime

not Utc

, you will not get the Z

ISO8601 end-of-line extension. The example you provided is present Z

because it DateTime.Parse

recognizes it and returns DateTime

in Utc

. If it is Z

missing from the original string you are parsing, you can still accept UTC by using ToUniversalTime()

in an object with a date.

+7


source


The answer is pretty much what @Dirk said:

parsedDate.ToString("O")

is a string, but you need to convert the DateTime to UTC: as you get the "Z" at the end.

See https://msdn.microsoft.com/en-us/library/az4se3k1%28v=vs.110%29.aspx for details .



Edit:

To convert DateTime to UTC use the method ToUniversalTime()

.

+4


source







All Articles