考虑到:

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

其他回答

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

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

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

正如在其他回答中提到的,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);
    });

使用Newtonsoft。Json,你可以这样做

JsonConvert.SerializeObject(DateTime.UtcNow)

例如:https://dotnetfiddle.net/O2xFSl

DateTime.Now.ToString("yyyy-MM-dd'T'HH:mm:ss zzz");

DateTime.Now.ToString("O");

注意:根据您在终端所做的转换,您将使用第一行(最接近它)或第二行。

确保只在本地时间应用格式,因为“zzz”是UTC转换的时区信息。