考虑到:

DateTime.UtcNow

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

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

yyyy-MM-ddTHH:mm:ssZ

当前回答

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);
    });

像2018-06-22T13:04:16这样的格式可以在API的URI中传递:

public static string FormatDateTime(DateTime dateTime)
{
    return dateTime.ToString("s", System.Globalization.CultureInfo.InvariantCulture);
}
DateTime.UtcNow.ToString("s")

返回类似2008-04-10T06:30:00的内容

UtcNow显然返回UTC时间,所以在以下情况下没有伤害:

string.Concat(DateTime.UtcNow.ToString("s"), "Z")

读者注意:一些评论指出了这个答案中的一些问题(特别是与第一个建议有关)。更多信息请参考评论部分。

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

使用自定义日期-时间格式,这将为您提供类似于 2008 - 09 - 22 - t13:57:31.2311892内。

另一种方法是:

DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture);

它使用标准的“往返”风格(ISO 8601)来给你 2008 - 09 - 22 - t14:01:54.9571247z。

要获得指定的格式,您可以使用:

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

DateTime.UtcNow。ToString("s", System.Globalization.CultureInfo.InvariantCulture)应该给你你想要的,因为"s"格式说明符被描述为一个可排序的日期/时间模式;符合ISO 8601标准。

编辑:为了得到OP要求的额外Z,使用“o”而不是“s”。