TimeSpan.Parse时间格式hhmmss

在c#我有时间格式hhmmss喜欢124510 12:45:10我需要知道TotalSeconds。 我使用了TimeSpan.Parse(“12:45:10”)。ToTalSeconds但它不采用格式hhmmss。 转换它的任何好方法?

这可能有所帮助

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(); } } } 

请注意,这将不会处理24小时的时间,要解析24HR格式的时间,您应该使用模式HHmmss

将字符串解析为DateTime值,然后减去它的Date值以获得TimeSpan的时间:

 DateTime t = DateTime.ParseExact("124510", "HHmmss", CultureInfo.InvariantCulture); TimeSpan time = t - t.Date; 

您必须确定接收时间格式并将其转换为任何一致的格式。

然后,您可以使用以下代码:

格式: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 

格式: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 

如果格式不匹配,将抛出FormatException并显示消息:“ 字符串未被识别为有效的DateTime”。

你需要逃避冒号(或其他分隔符),因为它无法处理它们,我不知道。 请参阅MSDN上的自定义TimeSpan格式字符串 ,以及Jon接受的答案,以及为什么TimeSpan.ParseExact不起作用 。

如果你能保证字符串永远是hhmmss,你可以这样做:

 TimeSpan.Parse( timeString.SubString(0, 2) + ":" + timeString.Substring(2, 2) + ":" + timeString.Substring(4, 2)))