user2835256
user2835256

Reputation: 415

Conversion to 12-hour format is not working

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();

Upvotes: 3

Views: 99

Answers (1)

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

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.

Upvotes: 11

Related Questions