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

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

    As mentioned in other answer, DateTime has issues by design.

    NodaTime

    I suggest to use NodaTime to manage date/time values:

    • Local time, date, datetime
    • Global time
    • Time with timezone
    • Period
    • Duration

    Formatting

    So, to create and format ZonedDateTime you can use the following code snippet:

    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
    
    

    For me NodaTime code looks quite verbose. But types are really useful. They help to handle date/time values correctly.

    Newtonsoft.Json

    To use NodaTime with Newtonsoft.Json you need to add reference to NodaTime.Serialization.JsonNet NuGet package and configure JSON options.

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

提交回复
热议问题