考虑到:

DateTime.UtcNow

我如何获得一个字符串,它表示在ISO 8601兼容的格式相同的值?

请注意,ISO 8601定义了许多类似的格式。我想要的具体格式是:

yyyy-MM-ddTHH:mm:ssZ

当前回答

System.DateTime.UtcNow.ToString("o")

=>

val it : string = "2013-10-13T13:03:50.2950037Z"

其他回答

大多数答案都是毫秒/微秒,这显然是ISO 8601不支持的。正确答案应该是:

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

引用:

ISO 8601规范 “K”说明符

The "s" standard format specifier represents a custom date and time format string that is defined by the DateTimeFormatInfo.SortableDateTimePattern property. The pattern reflects a defined standard (ISO 8601), and the property is read-only. Therefore, it is always the same, regardless of the culture used or the format provider supplied. The custom format string is "yyyy'-'MM'-'dd'T'HH':'mm':'ss". When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture.

-来自MSDN

正如在其他回答中提到的,DateTime在设计上存在问题。

野田时间

我建议使用NodaTime来管理日期/时间值:

本地时间,日期,datetime 全球时间 带时区的时间 期 持续时间

格式化

因此,要创建并格式化ZonedDateTime,您可以使用以下代码片段:

var instant1 = Instant.FromUtc(2020, 06, 29, 10, 15, 22);

var utcZonedDateTime = new ZonedDateTime(instant1, DateTimeZone.Utc);
utcZonedDateTime.ToString("yyyy-MM-ddTHH:mm:ss'Z'", CultureInfo.InvariantCulture);
// 2020-06-29T10:15:22Z


var instant2 = Instant.FromDateTimeUtc(new DateTime(2020, 06, 29, 10, 15, 22, DateTimeKind.Utc));

var amsterdamZonedDateTime = new ZonedDateTime(instant2, DateTimeZoneProviders.Tzdb["Europe/Amsterdam"]);
amsterdamZonedDateTime.ToString("yyyy-MM-ddTHH:mm:ss'Z'", CultureInfo.InvariantCulture);
// 2020-06-29T12:15:22Z

对我来说,NodaTime代码看起来相当冗长。但是类型真的很有用。它们有助于正确处理日期/时间值。

Newtonsoft。Json

使用Newtonsoft的NodaTime。您需要添加引用到NodaTime.Serialization.JsonNet NuGet包并配置Json选项。

services
    .AddMvc()
    .AddJsonOptions(options =>
    {
        var settings=options.SerializerSettings;
        settings.DateParseHandling = DateParseHandling.None;
        settings.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
    });

如果你在SharePoint 2010或更高版本下开发,你可以使用

using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
...
string strISODate = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now)

我将使用XmlConvert:

XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.RoundtripKind);

它会自动保存时区。