Search code examples
c#datetimewindows-phone-8.1windows-rt

Convert DateTime to a specific format


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

2015-03-26T18:02:58.145798Z

Currently I receive a date from a server and I'm able to parse it and convert the date in to DateTime and the ToString() output is something like this:

26/03/2015 18:02:58

For converting the date I'm using 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 the original format?

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


Solution

  • If you have a DateTime object you can convert it to a string with that particular format by using O as format specifier:

    parsedDate.ToString("O")
    

    or

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

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


    If the DateTimeKind of your DateTime object is not Utc then you won't get the Z extension at the end of the string according to ISO8601. In the example you provided the Z is present because DateTime.Parse will recognize it and return a DateTime in Utc. Should the Z be missing in the original string you parse you can still assume it's UTC by using ToUniversalTime() on the date time object.