AM / PM到TimeSpan [英] AM/PM to TimeSpan

查看:73
本文介绍了AM / PM到TimeSpan的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现,即我要将格式为 hh:mm tt 字符串转换为 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.

例如,转换 09:45 pm 21:45:00

推荐答案

最简单的方法可能是是使用 DateTime.ParseExact 将其解析为 DateTime ,然后使用 TimeOfDay 精确到 TimeSpan

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;

奇怪的是,当您还 / em>但指定一个am / pm指示符。您可能希望格式字符串中用 h代替 hh,以允许用 9:45 pm代替 09:45 pm。

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还会说起初这是 TimeSpan 的奇怪用法,但是在我看来,.NET日期/时间类型有些混乱。使用 Noda时间,但我有偏见:)

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

这篇关于AM / PM到TimeSpan的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆