Given a DateTime object, how do I get an ISO 8601 date in string format?

后端 未结 18 2440
暖寄归人
暖寄归人 2020-11-22 02:15

Given:

DateTime.UtcNow

How do I get a string which represents the same value in an ISO 8601-compliant format?

Note that ISO 8601 de

18条回答
  •  孤城傲影
    2020-11-22 02:19

    You have a few options including the "Round-trip ("O") format specifier".

    var date1 = new DateTime(2008, 3, 1, 7, 0, 0);
    Console.WriteLine(date1.ToString("O"));
    Console.WriteLine(date1.ToString("s", System.Globalization.CultureInfo.InvariantCulture));
    

    Output

    2008-03-01T07:00:00.0000000
    2008-03-01T07:00:00
    

    However, DateTime + TimeZone may present other problems as described in the blog post DateTime and DateTimeOffset in .NET: Good practices and common pitfalls:

    DateTime has countless traps in it that are designed to give your code bugs:

    1.- DateTime values with DateTimeKind.Unspecified are bad news.

    2.- DateTime doesn't care about UTC/Local when doing comparisons.

    3.- DateTime values are not aware of standard format strings.

    4.- Parsing a string that has a UTC marker with DateTime does not guarantee a UTC time.

提交回复
热议问题