Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short Time with DateTime.ParseExact

I’m trying to parse a time. I’ve seen this question asked/answered here many times but not for this specific scenario. Here’s my code:

var time1 = DateTime.ParseExact("919", "Hmm", CultureInfo.InvariantCulture);

also

var time2 = DateTime.ParseExact("919", "Hmm", null);

both of these throw the same

"String was not recognized as a valid DateTime"

What I want is 9:19 AM.

For further info I also need to parse “1305” as 1:05 PM, this is working fine.

It seems to me I’m using the correct format. What am I overlooking?

like image 694
Alex Avatar asked May 18 '26 11:05

Alex


2 Answers

I'm not sure there is any format that can handle this. The problem is that "H" can be either one digit or two, so if there are two digits available, it will grab both - in this case parsing it as hour 91, which is clearly invalid.

Ideally, you'd change the format to HHmm - zero-padding the value where appropriate - so "0919" would parse fine. Alternatively, use a colon in the format, to distinguish between the hours and the minutes. I don't believe there's any way of making DateTime parse a value of "919" as you want it to... so you'll need to adjust the string somehow before parsing it. (We don't have enough context to recommend a particular way of doing that.)

like image 98
Jon Skeet Avatar answered May 21 '26 03:05

Jon Skeet


Yes, your format is right but since H specifier might be 2 character, ParseExact method try to parse 91 as an hour, which is an invalid hour, that's why you get FormatException in both case.

I connected to microsoft team about this situation 4 months ago. Take a look;

  • DateTime conversion from string C#

They suggest to use 2 digit form in your string or insert a date separator between them.

var time1 = DateTime.ParseExact("0919", "Hmm", CultureInfo.InvariantCulture);

or

var time1 = DateTime.ParseExact("9:19", "H:mm", CultureInfo.InvariantCulture);
like image 45
Soner Gönül Avatar answered May 21 '26 04:05

Soner Gönül



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!