Given a DateTime object, how do I get an ISO 8601

2018-12-31 07:04发布

Given:

DateTime.UtcNow

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

Note that ISO 8601 defines a number of similar formats. The specific format I am looking for is:

yyyy-MM-ddTHH:mm:ssZ

15条回答
忆尘夕之涩
2楼-- · 2018-12-31 07:45

If you must use DateTime to ISO 8601, then ToString("o") should yield what you are looking for. For example,

2015-07-06T12:08:27

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.

查看更多
妖精总统
3楼-- · 2018-12-31 07:45

Most of these answers have milliseconds / microseconds which clearly isn't supported by ISO 8601. The correct answer would be:

System.DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssK");
// or
System.DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssK");

References:

查看更多
刘海飞了
4楼-- · 2018-12-31 07:46

To format like 2018-06-22T13:04:16 which can be passed in the URI of an API use:

public static string FormatDateTime(DateTime dateTime)
{
    return dateTime.ToString("s", System.Globalization.CultureInfo.InvariantCulture);
}
查看更多
初与友歌
5楼-- · 2018-12-31 07:48
System.DateTime.UtcNow.ToString("o")

=>

val it : string = "2013-10-13T13:03:50.2950037Z"
查看更多
低头抚发
6楼-- · 2018-12-31 07:52

To convert DateTime.UtcNow to a string representation of yyyy-MM-ddTHH:mm:ssZ, you can use the ToString() method of the DateTime structure with a custom formatting string. When using custom format strings with a DateTime, it is important to remember that you need to escape your seperators using single quotes.

The following will return the string represention you wanted:

DateTime.UtcNow.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", DateTimeFormatInfo.InvariantInfo)
查看更多
临风纵饮
7楼-- · 2018-12-31 07:53
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

查看更多
登录 后发表回答