TimeSpan.Parse time format hhmmss

2019-01-23 15:48发布

问题:

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?

回答1:

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.



回答2:

Parse the string to a DateTime value, then subtract it's Date value to get the time as a TimeSpan:

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


回答3:

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)

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)

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."



回答4:

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 Strings on MSDN, and the accepted answer, from Jon, to Why does TimeSpan.ParseExact not work.



回答5:

If you can guarantee that the string will always be hhmmss, you could do something like:

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


标签: c# timespan