Beware of TimeSpan.Parse

I am in the process of building a custom configuration section, and as a part of it, I need a TimeSpan property. I have struggled a bit with figuring out the format to use for TimeSpan in the string value in the config file, never getting 24 hours to be one day, no matter if I specify "00:24:00" or 24:00:00.

After a bit of debugging, I found out that TimeSpan.Parse uses some fuzzy logic to find out if you mean days or hours in the first part of the value. Notice the difference between parsing "23:00:00", which evaluates to 23 hours, and "24:00:00", which evaluates to 24 days.

? TimeSpan.Parse("23:00:00")
{23:00:00}
    Days: 0
    Hours: 23
    Milliseconds: 0
    Minutes: 0
    Seconds: 0
    Ticks: 828000000000
    TotalDays: 0.95833333333333326
    TotalHours: 23.0
    TotalMilliseconds: 82800000.0
    TotalMinutes: 1380.0
    TotalSeconds: 82800.0
? TimeSpan.Parse("24:00:00")
{24.00:00:00}
    Days: 24
    Hours: 0
    Milliseconds: 0
    Minutes: 0
    Seconds: 0
    Ticks: 20736000000000
    TotalDays: 24.0
    TotalHours: 576.0
    TotalMilliseconds: 2073600000.0
    TotalMinutes: 34560.0
    TotalSeconds: 2073600.0

So, if you actually want to specify 24 hours as a TimeSpan, you need to specify it as one day, with hours, minutes and seconds, like this: "1.00:00:00":

? TimeSpan.Parse("1.00:00:00")
{1.00:00:00}
    Days: 1
    Hours: 0
    Milliseconds: 0
    Minutes: 0
    Seconds: 0
    Ticks: 864000000000
    TotalDays: 1.0
    TotalHours: 24.0
    TotalMilliseconds: 86400000.0
    TotalMinutes: 1440.0
    TotalSeconds: 86400.0
Advertisements
This entry was posted in .NET. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s