【发布时间】:2017-10-02 12:57:05
【问题描述】:
我正在尝试将时间戳字符串转换为 TimeSpan 对象。
但是,TimeSpan.Parse() 并没有像我预期的那样工作。我会解释原因。
我想转换两种类型的时间戳。
- 分:秒
例如30:53,1:23,0:05 - 时:分:秒
例如1:30:53,2:1:23,0:0:3
问题是,类型 1 在TimeSpan.Parse() 方法中被解释为小时:分钟格式。
Console.WriteLine(TimeSpan.Parse("12:43"));
// the result I expect -> 0:12:43
// the actual result -> 12:43:00
我用谷歌搜索了这个问题并找到了这个 SO 帖子。
Parse string in HH.mm format to TimeSpan
这使用DateTime.ParseExact() 来解析特定格式的字符串。但是,问题是我需要为类型 1 和 2 使用不同的格式。
// ok
var ts1 = DateTime.ParseExact("7:33", "m:s", CultureInfo.InvariantCulture).TimeOfDay;
// throws an exception
var ts2 = DateTime.ParseExact("1:7:33", "m:s", CultureInfo.InvariantCulture).TimeOfDay;
// throws an exception
var ts3 = DateTime.ParseExact("7:33", "h:m:s", CultureInfo.InvariantCulture).TimeOfDay;
// ok
var ts4 = DateTime.ParseExact("1:7:33", "h:m:s", CultureInfo.InvariantCulture).TimeOfDay;
我还查看了 MSDN,但没有帮助。
https://msdn.microsoft.com/ja-jp/library/se73z7b9(v=vs.110).aspx
所以我想出的解决方案如下。
A. DateTime.ParseExact 与 if
string s = "12:43";
TimeSpan ts;
if (s.Count(c => c == ':') == 1)
ts = DateTime.ParseExact(s, "m:s", CultureInfo.InvariantCulture).TimeOfDay;
else
ts = DateTime.ParseExact(s, "h:m:s", CultureInfo.InvariantCulture).TimeOfDay;
B. TimeSpan.Parse 与 if
string s = "12:43";
if (s.Count(c => c == ':') == 1)
s = "0:" + s;
var ts = TimeSpan.Parse(s);
但它们都很长而且不“酷”。感觉就像我在重新发明轮子。我不想要他们,任何接受者?
那么将 h:m:s 和 m:s 字符串转换为 TimeSpan 对象的简单方法是什么?
提前致谢!
【问题讨论】:
标签: c# datetime datetime-format