Runtime: Odd TimeSpan.Parse behavior

Created on 7 Sep 2017  路  3Comments  路  Source: dotnet/runtime

Hi All,

I found an odd TmeSpan.Parse behavior today that I wanted to share.

If you do TimeSpan.Parse 23:00:00 you get 23 hours whereas if you do the same with 24:00:00 you get 24 days.
You can run this code:

    static void Main(string[] args)
    {
        TestTime("23:00:00");
        TestTime("24:00:00");
    }

    private static void TestTime(string timeSpanStr)
    {
        TimeSpan ts = TimeSpan.Parse(timeSpanStr);
        Console.WriteLine($"TimeSpan.Parse({timeSpanStr}) returns {ts.Days} Days and {ts.Hours} Hours");
    }

Here is the console output:
TimeSpan.Parse(23:00:00) returns 0 Days and 23 Hours
TimeSpan.Parse(24:00:00) returns 24 Days and 0 Hours

I'm compiling to target .Net 4.5.2.
I have several .Net SDKs installed on my machine including 4.5.2 and 4.6.1.

Thanks!

Ziv.

Most helpful comment

Looking at the regex in the remarks section on MSDN: https://msdn.microsoft.com/en-us/library/se73z7b9(v=vs.110).aspx, 24:00:00 should not have been accepted as a valid input and it should have thrown a FormatException.

I opened a doc issue https://github.com/dotnet/docs/issues/3081 so that at least the TimeSpan.Parse behavior and documented would align.

Thanks!

Ziv.

All 3 comments

While I agree it's confusing, it's also by design. TimeSpan.Parse has heuristics to try to figure out what pattern is being used, and since 24 isn't a valid number of hours, it discards hh:mm:ss as a pattern and looks for others that could work, settling on dd:hh:mm. If you were to instead use TimeSpan.ParseExact("24:00:00", "c", null), for example, it'll fail to parse.
cc: @tarekgh

@stephentoub is right. "24:00:00 is not a valid time. this is by design and we always recommend to use ParseExact to avoid heuristic parsing.

Looking at the regex in the remarks section on MSDN: https://msdn.microsoft.com/en-us/library/se73z7b9(v=vs.110).aspx, 24:00:00 should not have been accepted as a valid input and it should have thrown a FormatException.

I opened a doc issue https://github.com/dotnet/docs/issues/3081 so that at least the TimeSpan.Parse behavior and documented would align.

Thanks!

Ziv.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jamesqo picture jamesqo  路  3Comments

nalywa picture nalywa  路  3Comments

EgorBo picture EgorBo  路  3Comments

jzabroski picture jzabroski  路  3Comments

chunseoklee picture chunseoklee  路  3Comments