Converting minutes to hours only
Asked Answered
I

5

7

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 ?

Inauspicious answered 15/1, 2018 at 9:9 Comment(0)
D
16

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}";
Deadening answered 15/1, 2018 at 9:13 Comment(0)
P
8

You need to use TotalHours on the TimeSpan object.

string.Format("{0}:{1}",
    (int) hours.TotalHours,
    hours.Minutes);
Pleonasm answered 15/1, 2018 at 9:12 Comment(0)
R
1

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}";
Rolfston answered 15/1, 2018 at 9:26 Comment(0)
S
0

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}"
Strained answered 15/1, 2018 at 9:11 Comment(3)
This gives Unhandled Exception: System.FormatException: Format specifier was invalid.Ceratodus
Just use string.Format("{0}:{1}",(int)minutes/60, minutes%60) or $"{(int)minutes/60}:{minutes%60}"Vookles
@MatthewWatson: The exception can be fixed by casting the result. Found this here Standard Numeric Format Strings D -- Supported by: Integral types only. So this should work with string.Format("{0:D2}:{1:D2}",(int)minutes/60, (int)minutes%60)Vookles
S
0
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
Seniority answered 15/1, 2018 at 9:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.