TimeSpan.Parse time format hhmmss

天大地大妈咪最大 提交于 2019-11-29 01:32:24

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.

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;

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

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

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)))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!