3

I'm using .NET 4 and getting Input string not in correct format error when executing the following:

TimeSpan dropTime=TimeSpan.ParseExact("01:33 PM", "hh:mm tt", CultureInfo.InvariantCulture);

What am I doing wrong? I tried with the TT too, just in case but that do it. Otherwise my format seems to match?

3 Answers 3

7

tt is not a valid format specifier for TimeSpan as can be seen on MSDN.

What you are trying to parse is a time not a TimeSpan - PM specifies a time of day, not a time interval (which is what TimeSpan represents) and cannot be parsed directly by TimeSpan.

You can use DateTime to parse this first and get the TimeSpan from it:

DateTime.ParseExact("01:33 PM", "hh:mm tt", CultureInfo.InvariantCulture).TimeOfDay
1
  • Thanks. So I'm assuming I need to first parse it to a DateTime.
    – Rivka
    Jun 14, 2012 at 18:04
3

You have to use the class DateTime instead:

TimeSpan dropTime=DateTime.ParseExact("01:33 PM", "hh:mm tt", CultureInfo.InvariantCulture).TimeOfDay;
0
0

Just use DateTime object, please see my sample code:

DateTime dropTime = new DateTime();
DateTime.TryParse("01:33 PM", out dropTime);

This will parse your string into datetime.

Best regards, Gregor Primar

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.