我想实现 this 的逆过程,也就是说,我想将格式为 hh:mm tt
的 string
转换为秒数为零的 TimeSpan
。
例如,09:45 pm
转换为 21:45:00
。
最佳答案
最简单的方法可能是使用 DateTime.ParseExact
将其解析为 DateTime
,然后使用 TimeOfDay
精确 TimeSpan
。
DateTime dateTime = DateTime.ParseExact(text,
"hh:mm tt", CultureInfo.InvariantCulture);
TimeSpan span = dateTime.TimeOfDay;
当您还指定 am/pm 指示符时,在多个小时中看到前导 0 是很奇怪的。您可能希望在格式字符串中使用“h”而不是“hh”,以允许使用“9:45 pm”而不是“09:45 pm”。
(我还认为,首先是 TimeSpan
的一种奇怪用法,但在我看来,.NET 日期/时间类型有些困惑。我建议使用Noda Time ,但我有偏见 :)
关于c# - 上午/下午到时间跨度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17553738/