Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion to 12-hour format is not working

Tags:

c#

.net

asp.net

I wrote that code below to convert AM/PM to 12-Hour conversion. This code work fines for AM but it is not working for PM and generates error that Provided string for conversion is invalid. Please anyone answer my question?

string st = "10:01 PM";
DateTime t = DateTime.ParseExact(st, "H:mm tt", CultureInfo.InvariantCulture);
TimeSpan ts = t.TimeOfDay;
editslug.Text = t.TimeOfDay.ToString();
like image 233
user2835256 Avatar asked Feb 03 '26 07:02

user2835256


1 Answers

That's because H is the 24 hour clock. You need to use h.

DateTime t = DateTime.ParseExact(st, "h:mm tt", CultureInfo.InvariantCulture);

I also argue that you might be looking for hh if times come in like this 01:14 AM for times less than 10. However, I don't know enough about your data to be sure about that.

like image 182
Mike Perrenoud Avatar answered Feb 04 '26 21:02

Mike Perrenoud