Howdy

I have a timespan that contain in excess of 24 hours. For the example lets use a value of 1 day 6 hours and 32 minutes.

I would like to get this into a string that displays "30:32".

Have so far tried something along the lines of string.Format("{0}:{1}", TimeSpan.TotalHours, TimeSpan.Minutes) however this gives me a scenario where it'll display 13:0 rather than 13:00 which I also failed to resolve.

Recommended Answers

All 2 Replies

Here is a one solution

    TimeSpan timeSpan;
    string timeStr;
    int totalHours;
    int totalMinutes;

    // 1 day, 6 hrs, 32 mins, 0 secs, 0 msecs
    timeSpan = new TimeSpan(1, 6, 32, 0, 0); 
    // Get hours and minutes
    // TotalHours is of type double, cast it to integer (truncate to integer)
    totalHours = (int)timeSpan.TotalHours;
    // Remove totalHours hours from the timeSpan to avoid rounding error
    timeSpan = timeSpan.Subtract(new TimeSpan(totalHours, 0, 0)); // hours, 0 mins, 0 secs
    // TotalMinutes is of type double, cast it to integer (truncate to integer)
    totalMinutes = (int)timeSpan.TotalMinutes;
    // Convert to a string
    timeStr = string.Format("{0:d2}:{1:d2}", totalHours, totalMinutes);
    // Display result
    MessageBox.Show(timeStr);

Notice that I created timespan with explicit seconds and milliseconds. You may have got this one wrong. I subtracted (total) hours from the timespan. After that it has only minutes (and seconds and mseconds) left. To format with two digits you can use for example "d2".

HTH

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.