TimeSpan.Parse time format hhmmss

后端 未结 6 1500
忘掉有多难
忘掉有多难 2020-12-15 20:52

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 tak

相关标签:
6条回答
  • 2020-12-15 21:04

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

    0 讨论(0)
  • 2020-12-15 21:15

    In case you want to work with also milliseconds like this format "01:02:10.055" then you may do as following;

    public static double ParseTheTime(string givenTime)
    {
    var time = DateTime.ParseExact(givenTime, "hh:mm:ss.fff", CultureInfo.InvariantCulture);
    return time.TimeOfDay.TotalSeconds;
    }
    

    This code will give you corresponding seconds. Note that you may increase the number of 'f's if you want to adjust precision points.

    0 讨论(0)
  • 2020-12-15 21:21

    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;
    
    0 讨论(0)
  • 2020-12-15 21:27

    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.

    0 讨论(0)
  • 2020-12-15 21:29

    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.

    0 讨论(0)
  • 2020-12-15 21:30

    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)))
    
    0 讨论(0)
提交回复
热议问题