Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TimeSpan.TryParseExact not working

Tags:

c#

I'm trying to retrieve a timespan from a string, but TryParseExact is returning false (fail).

I can't see what I'm doing wrong, can you help? I've tried 2 versions of my line in the code, both do not work.

TimeSpan.TryParseExact("04:00:01","HH:mm:ss",CultureInfo.CurrentCulture, out aTime) 

and

TimeSpan.TryParseExact("04:00:01","HH:mm:ss", null, out aTime) 

EDIT: both responses here are correct, I have the wrong format for my custom timespan format - the mistake I made is to assume that the custom formats for DateTime would work for TimeSpans, but they do not.

like image 651
mcmillab Avatar asked Oct 24 '12 03:10

mcmillab


2 Answers

The problem is simply in the format string for the TimeSpan, you have specified "HH:mm:ss". The specifier HH (upper case) is not valid for timespan. You should use hh. Format strings are indeed case sensitive.

The colon character (:) also needs to be escaped, so use "hh\\:mm\\:ss", @"hh\:mm\:ss" or "hh':'mm':'ss". All three forms will have the same effect.

You can review a list of valid custom format strings for TimeSpan here. and the standard format strings for TimeSpan are here.

While HH is valid for DateTime and DateTimeOffset where it represents the 24 hour clock and lower case hh represents a 12 hour clock, For TimeSpan - the hours component is always based on 24 hours. You would think that the HH format would be the one chosen, for uniformity, but nope - it's hh.

like image 157
Matt Johnson-Pint Avatar answered Sep 21 '22 11:09

Matt Johnson-Pint


It's probably should get mentioned that you need to escape the colon character.

TryParseExact("04:00:01", "HH\\:mm\\:ss" ... 
like image 31
Oğuz Yıldız Avatar answered Sep 18 '22 11:09

Oğuz Yıldız