tags:

views:

5821

answers:

5

Exact Duplicate

Timespan formatting

First question here:

I have two DateTime vars, beginTime and endTime. I have gotten the difference of them by doing the following:

TimeSpan dateDifference = endTime.Subtract(beginTime);

How can I now return a string of this in hh hrs, mm mins, ss secs format using C#.

If the difference was 00:06:32.4458750

It should return this 00 hrs, 06 mins, 32 secs

Thanks for the help

+1  A: 

Would TimeSpan.ToString() do the trick for you? If not, it looks like the code sample on that page describes how to do custom formatting of a TimeSpan object.

Andy
Getting page no found on link.
automatic
I got the same, searched again and updated the link. Does this one work for you?
Andy
+2  A: 

The easiest way to format a TimeSpan is to add it to a DateTime and format that:

string formatted = (DateTime.Today + dateDifference).ToString("HH 'hrs' mm 'mins' ss 'secs'");

This works as long as the time difference is not more than 24 hours.

The Today property returns a DateTime value where the time component is zero, so the time component of the result is the TimeSpan value.

Guffa
+6  A: 

Use String.Format() with multiple parameters.

using System;

namespace TimeSpanFormat
{
    class Program
    {
     static void Main(string[] args)
     {
      TimeSpan dateDifference = new TimeSpan(0, 0, 6, 32, 445);
      string formattedTimeSpan = string.Format("{0:D2} hrs, {1:D2} mins, {2:D2} secs", dateDifference.Hours, dateDifference.Minutes, dateDifference.Seconds);
      Console.WriteLine(formattedTimeSpan);
     }
    }
}
GBegen
+2  A: 

According to the Microsoft documentation, the TimeSpan structure exposes Hours, Minutes, Seconds, and Milliseconds as integer members. Maybe you want something like:

dateDifference.Hours.ToString() + " hrs, " + dateDifference.Minutes.ToString() + " mins, " + dateDifference.Seconds.ToString() + " secs"
Jason 'Bug' Fenter
+2  A: 

By converting it to a datetime, you can get localized formats:

new DateTime(timeSpan.Ticks).ToString("hh:mm");
vdboor
Be sure to use a "HH", not "hh", as a format specifier, otherwise an hours value of 0 might be printed out as "12" - I'm guessing the interpretation of the format specifiers depends on the locale settings.
weiji
Also, this has the same issue as Guffa's - if an elapsed time is e.g. 26 hours long, it prints out as "02:00" hours. But I highly prefer this way of printing out formatted strings.
weiji