Reputation: 9738
I am converting minutes into hours. So if I have minutes = 12534
. The result should be 208:54
. The below code fails to bring this result.
TimeSpan spWorkMin = TimeSpan.FromMinutes(12534);
string workHours = spWorkMin.ToString(@"hh\:mm");
Console.WriteLine(workHours);
The result is 16:54
.
How to get it correct?
Upvotes: 14
Views: 42841
Reputation: 103
using System;
var days = 1;
var hours = 23; //max 23
var min = 12; //max 59
var TotalMin = (days*24*60)+(hours*60)+min;
Console.WriteLine("TotalMins "+ TotalMin);
//return back to the original days,hours,minutes
var Days = (TotalMin/(24*60));
var _minutes = (TotalMin%(60*60));
var Hours = (_minutes/60);
var Minutes = _minutes - (Hours*60);
Console.WriteLine($"{Days} , {Hours} , {Minutes}");
Upvotes: 0
Reputation: 260
Personnaly I use this:
public static double MinutsTohHours(int Minuti)
{
double Tempo = 0;
Tempo = ((double)(Minuti % 60) / 100);
var n = (double)Minuti / 60;
return Math.Floor((double)Minuti / 60) + Tempo;
}
Upvotes: 0
Reputation: 50672
var totalMinutes = 12534;
Console.WriteLine("{0:00}:{1:00}", totalMinutes / 60, totalMinutes % 60);
Or
var totalMinutes = 12534;
var time = TimeSpan.FromMinutes(totalMinutes);
Console.WriteLine("{0:00}:{1:00}", (int)time.TotalHours, time.Minutes);
See https://dotnetfiddle.net/gYEsj2 to play with this
Upvotes: 19
Reputation: 471
From MSDN documentation:
The "hh" custom format specifier outputs the value of the TimeSpan::Hours property, which represents the number of whole hours in the time interval that is not counted as part of its day component.
One quick way of getting the result you want would be something like the following:
TimeSpan spWorkMin = TimeSpan.FromMinutes(12534);
string workHours = string.Format("{0}:{1:00}", (int)spWorkMin.TotalHours, spWorkMin.Minutes);
Console.WriteLine(workHours);
Upvotes: 0
Reputation: 7301
The correct way to use is not using the ToString
overload of DateTime
– because there is no possibility to show the TotalHours
there – but the string.Format
method:
string.Format("{0:00}:{1:00}", (int)spWorkMin.TotalHours, spWorkMin.Minutes);
Upvotes: 16
Reputation: 4230
You need use TimeSpan.TotalHours
Property
The TotalHours property represents whole and fractional hours, whereas the Hours
property represents whole hours.
TimeSpan spWorkMin = TimeSpan.FromMinutes(12534);
string workHours = spWorkMin.ToString(@"hh\:mm");
Console.WriteLine(spWorkMin.TotalHours);
https://dotnetfiddle.net/JRCLra
Upvotes: 4
Reputation: 73
TimeSpan spWorkMin = TimeSpan.FromMinutes(12534);
string workHours = string.Format("{0}:{1}", (int)spWorkMin.TotalHours, spWorkMin.Minutes);
Console.WriteLine(workHours);
Upvotes: 0
Reputation: 31143
The format specifier hh
will show the hour part, which is not the total hours. You have to manually create a string using TotalHours
cast into ints to show it as you want and add the minutes to that.
Upvotes: 1