Parse date of ISO 8601 value 24:00:00 fails

江枫思渺然 提交于 2020-02-03 07:02:51

问题


I'm trying to parse incoming date from data source (which cannot be changed). It gives me time in ISO 8601 format example: 2007-04-05T24:00.

How ever in .Net it fails to parse this as valid time.

The wikipedia states that it should be valid format. Wikipedia ISO 8601

Example from https://stackoverflow.com/a/3556188/645410

How can I do this without a nasty string check hack?

Example (fiddle: http://dotnetfiddle.net/oB7EZx):

var strDate = "2007-04-05T24:00";       
Console.WriteLine(DateTime.Parse(strDate, null, DateTimeStyles.RoundtripKind));

Throws:

The DateTime represented by the string is not supported in calendar System.Globalization.GregorianCalendar.


回答1:


Yes, .NET doesn't support this as far as I'm aware.

My Noda Time project does, but only partially: it can parse the value, but the value is just parsed to midnight at the start of the next day, and is never formatted as 24:00. There's nothing in the Noda Time conceptual model to represent "the end of the day".

Sample code to show what's possible:

using System;
using NodaTime;
using NodaTime.Text;

class Test
{
    static void Main()
    {
        string text = "2007-04-05T24:00";
        var pattern = LocalDateTimePattern.CreateWithInvariantCulture
             ("yyyy-MM-dd'T'HH:mm");
        var dateTime = pattern.Parse(text).Value;
        Console.WriteLine(pattern.Format(dateTime)); // 2007-04-06T00:00
    }
}

If you don't mind losing the difference between inputs of "2007-04-05T24:00" and "2007-04-05T00:00" then you're probably okay.



来源:https://stackoverflow.com/questions/20879834/parse-date-of-iso-8601-value-240000-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!