gpt4 book ai didi

c# - 什么是转换h :m:s and m:s strings to TimeSpan object?的简单方法

转载 作者:行者123 更新时间:2023-11-30 14:47:09 25 4
gpt4 key购买 nike

我正在尝试将时间戳字符串转换为 TimeSpan 对象。但是,TimeSpan.Parse() 没有像我预期的那样工作。我会解释原因。

我想转换两种类型的时间戳。

  1. 分:秒
    例如30:53, 1:23, 0:05
  2. 时:分:秒
    例如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

所以我想到的解决方案如下。

一个。 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 对象的简单方法是什么?

提前致谢!

最佳答案

您可以在 TimeSpan.ParseExact 中指定几种格式:

  string source = "17:29";

TimeSpan result = TimeSpan.ParseExact(source,
new string[] { @"h\:m\:s", @"m\:s" },
CultureInfo.InvariantCulture);

在上面的代码中,我们首先尝试 h:m:s 格式,如果第一种格式失败,然后尝试 m:s

测试:

  string[] tests = new string[] { 
// minutes:seconds
"30:53", "1:23", "0:05",
// hours:minutes:seconds
"1:30:53", "2:1:23", "0:0:3" };

var report = string.Join(Environment.NewLine, tests
.Select(test => TimeSpan.ParseExact(
test,
new string[] { @"h\:m\:s", @"m\:s" },
CultureInfo.InvariantCulture)));

Console.Write(report);

结果:

00:30:53
00:01:23
00:00:05
01:30:53
02:01:23
00:00:03

关于c# - 什么是转换h :m:s and m:s strings to TimeSpan object?的简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46525945/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com