gpt4 book ai didi

c# - 在 C# 中将不规则字符串转换为 TimeSpan

转载 作者:太空宇宙 更新时间:2023-11-03 19:17:57 27 4
gpt4 key购买 nike

我有几个格式如下的字符串:

"1:15"
":45"
"1:30:45"

我需要将它们转换为 TimeSpan,但是当我对其中一些(例如第一个)进行 TimeSpan.Parse 时,它​​会将其返回为 1 小时 15 分钟,而我希望它为 1 分 15 秒.

如有任何建议,我们将不胜感激!

最佳答案

您可以使用 TimeSpan.ParseExact 的重载允许您指定一个精确的数组 format specifiers .

var formats = new string[] {@"m\:s", @"\:s", ...};
var timeSpace = TimeSpan.ParseExact(input, formats, CultureInfo.CurrentCulture);

请注意 ParseExact 是在 .Net 4 中引入的

关于c# - 在 C# 中将不规则字符串转换为 TimeSpan,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14785012/

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