tags:

views:

13130

answers:

7

What is the best way to convert seconds into (Hour:Minutes:Seconds:Milliseconds) time?

Let's say I have 80 seconds, are there any specialized classes/techniques in .NET that would allow me to convert those 80 seconds into (00h:00m:00s:00ms) format like to DateTime or something?

A: 

Have you tried DateTime.Parse?

JaredPar
+31  A: 

Just use the TimeSpan class.

TimeSpan t = TimeSpan.FromSeconds( secs );

string answer = string.Format("{0:D2}h:{1:D2}m:{2:D2}s:{3:D3}ms", 
       t.Hours, 
       t.Minutes, 
       t.Seconds, 
       t.Milliseconds);
CShipley
Clean and elegant.
Ariel
+2  A: 

If you know you have a number of seconds, you can create a TimeSpan value by calling TimeSpan.FromSeconds:

 TimeSpan ts = TimeSpan.FromSeconds(80);

You can then obtain the number of days, hours, minutes, or seconds. Or use one of the ToString overloads to output it in whatever manner you like.

Jim Mischel
+1  A: 
TimeSpan.FromSeconds(80);

http://msdn.microsoft.com/en-us/library/system.timespan.fromseconds.aspx

Jeremy Wilde
A: 

In VB.net, but its same same in C#

 Dim x As New TimeSpan(0, 0, 80)
 debug.print x.ToString()
'will print 00:01:20
Stefan
A: 

The TimeSpan constructor allows you to pass in seconds. Simply declare a variable of type TimeSpan amount of seconds. Ex:

TimeSpan span = new TimeSpan(0, 0, 500);
span.ToString();
Jim Petkus
A: 

I'd suggest you use the TimeSpan class for this.

public static void Main(string[] args)
{
    TimeSpan t = TimeSpan.FromSeconds(80);
    Console.WriteLine(t.ToString());

    t = TimeSpan.FromSeconds(868693412);
    Console.WriteLine(t.ToString());
}

Outputs:

00:01:20
10054.07:43:32
BeowulfOF