C# TimeSpan.Parse 时间格式 hhmmss
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1833830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TimeSpan.Parse time format hhmmss
提问by Julien Daniel
in c# i have time in format hhmmss like 124510 for 12:45:10 and i need to know the the TotalSeconds. i used the TimeSpan.Parse("12:45:10").ToTalSeconds but it does'nt take the format hhmmss. Any nice way to convert this?
在 C# 中,我有时间格式为 hhmmss,如 124510 为 12:45:10,我需要知道 TotalSeconds。我使用了 TimeSpan.Parse("12:45:10").ToTalSeconds 但它不采用 hhmmss 格式。有什么好的方法来转换这个吗?
采纳答案by Guffa
This might help
这可能有帮助
using System;
using System.Globalization;
namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
DateTime d = DateTime.ParseExact("124510", "hhmmss", CultureInfo.InvariantCulture);
Console.WriteLine("Total Seconds: " + d.TimeOfDay.TotalSeconds);
Console.ReadLine();
}
}
}
Note this will not handle 24HR times, to parse times in 24HR format you should use the pattern HHmmss.
请注意,这不会处理 24HR 时间,要解析24HR格式的时间,您应该使用模式HHmmss。
回答by Jeff Yates
If you can guarantee that the string will always be hhmmss, you could do something like:
如果您可以保证字符串始终为 hhmmss,则可以执行以下操作:
TimeSpan.Parse(
timeString.SubString(0, 2) + ":" +
timeString.Substring(2, 2) + ":" +
timeString.Substring(4, 2)))
回答by Guffa
Parse the string to a DateTime value, then subtract it's Date value to get the time as a TimeSpan:
将字符串解析为 DateTime 值,然后减去它的 Date 值以获取作为 TimeSpan 的时间:
DateTime t = DateTime.ParseExact("124510", "HHmmss", CultureInfo.InvariantCulture);
TimeSpan time = t - t.Date;
回答by ProfK
You need to escape the colons (or other separators), for what reason it can't handle them, I don't know. See Custom TimeSpan Format Stringson MSDN, and the accepted answer, from Jon, to Why does TimeSpan.ParseExact not work.
您需要转义冒号(或其他分隔符),它无法处理它们的原因是什么,我不知道。请参阅MSDN 上的Custom TimeSpan Format Strings,以及 Jon 对Why does TimeSpan.ParseExact not work接受的答案。
回答by Chirag
You have to decide the receiving time format and convert it to any consistent format.
您必须决定接收时间格式并将其转换为任何一致的格式。
Then, you can use following code:
然后,您可以使用以下代码:
Format: hh:mm:ss (12 Hours Format)
格式:hh:mm:ss(12 小时格式)
DateTime dt = DateTime.ParseExact("10:45:10", "hh:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
double totalSeconds = dt.TimeOfDay.TotalSeconds; // Output: 38170.0
Format: HH:mm:ss (24 Hours Format)
格式:HH:mm:ss(24 小时格式)
DateTime dt = DateTime.ParseExact("22:45:10", "HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
double totalSeconds = dt.TimeOfDay.TotalSeconds; // Output: 81910.0
In case of format mismatch, FormatException will be thrown with message: "String was not recognized as a valid DateTime."
如果格式不匹配,将抛出 FormatException 并显示消息:“ String 未被识别为有效的 DateTime。”