D.Iple
D.Iple

Reputation: 95

Converting minutes to hours only

I’m trying to solve this problem :

I’ve a large amount of minutes and I want to convert them into hours only, when I try with TimeSpan, it always shows days and hours.

My example code :

double minutes = 2000 ;
TimeSpan hours = TimeSpan.FromMinutes(minutes);
label1.Text = hours.ToString(@"hh\:mm");

The output result is 09:20 but I wanted this result 33:20

How can I convert minutes to get exact numbers of hours ?

Upvotes: 7

Views: 3715

Answers (5)

Paweł Dyl
Paweł Dyl

Reputation: 9143

Do it manually and use

string.Format("{0:D2}:{1:D2}",(int)minutes/60, (int)minutes%60)

or without casting:

string.Format("{0:00}:{1:00}", minutes/60, minutes%60)

Since C#6 with String Interpolation:

$"{minutes/60:00}:{minutes%60:00}"

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

Yet another possibility is to use 0 and 00 formatting strings in order to combine formatting and truncating:

double minutes = 2000;

// 2000 -> 33:20
// 1808 -> 30:08
//    8 -> 0:08
label1.Text = $"{minutes/60:0}:{minutes%60:00}";

If minutes can be negative, you should add Math.Abs:

// -2000 -> -33:20
label1.Text = $"{minutes/60:0}:{Math.Abs(minutes)%60:00}";

Upvotes: 1

chadalavada harish
chadalavada harish

Reputation: 65

public static void Main()
{
    //assigning values to variable
    double minutes = 2000;
    TimeSpan tspan = TimeSpan.FromMinutes(minutes); //converting minutes to timespan
    string res1 = (int)tspan.TotalHours +" Hours " + tspan.Minutes +" Minutes"; 

    string res2= (int)tspan.TotalHours + ":"+tspan.Minutes; 

    string res3= Convert.ToInt32(tspan.TotalHours)  + "."+tspan.Minutes +" Hours"; 

    Console.WriteLine(res1);
    Console.WriteLine(res2);
    Console.WriteLine(res3);
}

Output:

33 Hours 20 Minutes
33:20
33.20 Hours

Upvotes: 0

CodeFuller
CodeFuller

Reputation: 31282

This code produces the 33:20 result you're asking:

double minutes = 2000;
TimeSpan ts = TimeSpan.FromMinutes(minutes);
var res = $"{(int)ts.TotalHours}:{ts.Minutes}";

Upvotes: 16

NibblyPig
NibblyPig

Reputation: 52922

You need to use TotalHours on the TimeSpan object.

string.Format("{0}:{1}",
    (int) hours.TotalHours,
    hours.Minutes);

Upvotes: 8

Related Questions