Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

c# - AM/PM to TimeSpan

I want to achieve the converse of this, that is, I want to convert a string with format hh:mm tt to a TimeSpan with zeroed seconds.

For example, 09:45 pm is converted to 21:45:00.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...