tags:

views:

912

answers:

3

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?

A: 

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)))
Jeff Yates
i cant garantee that the string will always be hhmmss. I need to put the format in a .settings file
Julien Daniel
+3  A: 

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;
Guffa
DateTime.TimeOfDay gives you a TimeSpan straight off.
AakashM
You should use TimeOfDay instead of t - t.Date
Jeff Yates
A: 

Hi,

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.

Alan
i try and it works
Julien Daniel