AM/PM to TimeSpan
31,705
Solution 1
The simplest approach would probably be to parse it as a DateTime
using DateTime.ParseExact
, and then use the TimeOfDay
to exact the TimeSpan
.
DateTime dateTime = DateTime.ParseExact(text,
"hh:mm tt", CultureInfo.InvariantCulture);
TimeSpan span = dateTime.TimeOfDay;
It's odd to see a leading 0 on a number of hours when you're also specifying an am/pm designator though. You might want "h" instead of "hh" in the format string, to allow "9:45 pm" instead of "09:45 pm".
(I'd also argue that it's a strange use of TimeSpan
in the first place, but then the .NET date/time types are somewhat messed up in my view. I'd recommend using Noda Time, but I'm biased :)
Solution 2
This work for Me.
TimeSpan ts= DateTime.Parse("8:00 PM").TimeOfDay;
Related videos on Youtube
Author by
wjmolina
Updated on July 10, 2021Comments
-
wjmolina almost 3 years
I want to achieve the converse of this, that is, I want to convert a
string
with formathh:mm tt
to aTimeSpan
with zeroed seconds.For example,
09:45 pm
is converted to21:45:00
.-
Henk Holterman almost 11 yearsA
TimeSpan
does not have a format.
-
-
henon over 2 yearsBut it is not the only way.
DateTime.Parse("12:01 AM").TimeOfDay
did work for me too.