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

后端 未结 18 2221
暖寄归人
暖寄归人 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:29

    Note to readers: Several commenters have pointed out some problems in this answer (related particularly to the first suggestion). Refer to the comments section for more information.

    DateTime.UtcNow.ToString("yyyy-MM-ddTHH\\:mm\\:ss.fffffffzzz");
    

    This gives you a date similar to 2008-09-22T13:57:31.2311892-04:00.

    Another way is:

    DateTime.UtcNow.ToString("o");
    

    which gives you 2008-09-22T14:01:54.9571247Z

    To get the specified format, you can use:

    DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ")
    

    DateTime Formatting Options

提交回复
热议问题