Totalhours method displays minutes in wrong format

I have the below code which displays the totalhours, but the totalhours displays it differently for values less than 60 mins. That is for 35 mins or 45 mins (greater than 30mins) it displays as .533 and .75 respectively, and when I apply Convert.ToInt32() on these values it rounds it off to 1 which I don't want.

int imins = 31; 
TimeSpan ts = TimeSpan.FromMinutes(imins);           
Console.WriteLine(Convert.ToInt32( ts.TotalHours) +":" + ts.Minutes); //string.Format("{0:00}:{1:00}", 
Console.Read();

My intention is to display the time in format example hh:mm , but if I use total hours .lets say for displaying 31 mins the output I get is 01:31 which is wrong, it should be 00:31.

Total hours should only display the totalhours minus the minutes.

Jon Skeet
people
quotationmark

As you're using .NET 4, you can make your life much simpler by using TimeSpan.ToString(string) to do the formatting for you:

using System;

class Test
{
    static void Main()
    {
        int minutes = 31; 
        TimeSpan ts = TimeSpan.FromMinutes(minutes);
        string text = ts.ToString("h':'mm");
        Console.WriteLine(text); // 0:31
    }
}

EDIT: If you need it to go into multiple days but still only show the hours, I'm not sure that TimeSpan handles that. You can use a simple cast to int in that case:

using System;

class Test
{
    static void Main()
    {
        int minutes = 31; 
        TimeSpan ts = TimeSpan.FromMinutes(minutes);
        string text = string.Format("{0}:{1:mm}", (int) ts.TotalHours, ts);
        Console.WriteLine(text); // 0:31
    }
}

Or use my Noda Time library, which does support this:

using System;
using NodaTime;
using NodaTime.Text;

class Test
{
    static void Main()
    {
        Duration duration = Duration.FromMinutes(6000);
        var pattern = DurationPattern.CreateWithInvariantCulture("H:mm");
        string text = pattern.Format(duration);
        Console.WriteLine(text); // 0:31
    }
}

(That's assuming you want the output for 100 hours to be 100:00 rather than something like 4:04:00.)

people

See more on this question at Stackoverflow