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?
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
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);
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
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.
TimeSpan spWorkMin = TimeSpan.FromMinutes(12534);
string workHours = string.Format("{0}:{1}", (int)spWorkMin.TotalHours, spWorkMin.Minutes);
Console.WriteLine(workHours);
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);
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;
}
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}");
Related
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 ?
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}";
You need to use TotalHours on the TimeSpan object.
string.Format("{0}:{1}",
(int) hours.TotalHours,
hours.Minutes);
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}";
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
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}"
I have a problem with asp.net full calender. Actually when i am using it my events comes with time "80 min" format.
But i want it in "1:20 min" format
Please help me thanks in advance.
In order to accomplish your requirement,use TimeSpan.FromMinutes as shown below :-
var result = TimeSpan.FromMinutes(80);
TimeSpan.FromMinutes will give you an object that you can use in different ways as shown below.
var hours = (int)result.TotalHours;
var minutes = result.Minutes;
var time = string.Format("{0} : {1}", hours, minutes);
You can perform simple mathemetical calculations like this:
//minutes to be converted (70minutes = 1:10 hours)
int totalminutes = 70;
//total hours
int hours = 70 / 60;
//total minutes
int minutes = 70 % 60;
//output is 1:10
var time = string.Format("{0} : {1}", hours, minutes);
It is 8:30 and I am trying to find out how many seconds there are between now and the next whole hour (9:00). I think I just want to DateTime.Now.AddHours(1) but after I do that I think I need the "floor". How to get that value?
Thanks.
Just round the time of day in hours up to the next integral value:
var timeOfDay = DateTime.Now.TimeOfDay;
var nextFullHour = TimeSpan.FromHours(Math.Ceiling(timeOfDay.TotalHours));
var delta = (nextFullHour - timeOfDay).TotalSeconds;
//Completely misread. Completely re-writing
I woudl just do something Like this
int minutesToNextHour = 60 - DateTime.Now.Minutes;
int secondsToNextHour = minutesToNextHour * 60;
You don't have to mess around with ceilings and floors. The DateTime.Hour property represents whole hours (it is an integer beteen 0 and 23) of the time of the day represented by the DateTime. You can use this and the DateTime.Date property to strip the components of the DateTime you don't want (sub-hour data) and then just subtract as necessary to produce a TimeSpan.
var now = DateTime.Now;
var timeToNextHour = now.Date.AddHours(now.Hour + 1) - now;
You can of course extract the TotalSeconds component of the resulting TimeSpan if you want the result in seconds.
This seems to be the most simple:
3600 - DateTime.Now.TimeOfDay.TotalSeconds % 3600
(if you want it in whole numbers - integer - then prefix DateTime.Now... with (int).
So you'd need to subtract the 'remainder' minutes, find the difference, and multiply that by 60, right?
How about this:
var currentTime = DateTime.Now;
var hour = currentTime.AddHours(1).Hour;
var newTime = Convert.ToDateTime(hour + ":00");
var timespan = newTime.Subtract(currentTime);
var secondsDiff = timespan.TotalSeconds;
TimeSpan sec = new TimeSpan(0, 0, 3600 - (DateTime.Now.Minute * 60));
How about:
var now = DateTime.Now;
int secondsTillNextHour = (60 - now.Minute)*60+(60-now.Second);
Or (maybe clearer):
int SecondsTillNextHour = 3600 - 60*now.Minute - now.Second;
A more readable version:
public double SecondsToNextHour()
{
return SecondsToNextHour( DateTime.Now );
}
public double SecondsToNextHour( DateTime moment )
{
DateTime currentHour = new DateTime( moment.Year, moment.Month, moment.Day, moment.Hour, 0, 0 );
DateTime nextHour = currentHour.AddHours( 1 );
TimeSpan duration = nextHour - moment;
return duration.TotalSeconds;
}
TimeSpan result = (new DateTime(DateTime.Now.Year, DateTime.Now.Month,
DateTime.Now.Day, DateTime.Now.Hour + 1, 0, 0)).Subtract(DateTime.Now);
Basically here you are building a new DateTime that is one hour on from Now, with no minutes or seconds, then you subtract Now from this and have your result.
I would Timespan.Parse 08:30, add 1 hr to the object, then retrieve the hour part and build a new string with :00 as the minutes and reparse the new string. There may be a more efficient way to do this, but I find this technique clear to read.
in my application
Ex 1: Start time 12.30
(-)End time 16.00 here i get the value as 3.7 but i need to show this 3.7 as 3.5 in my application
Ex 2: Start time 12.00
(-)End time 16.00 here i get the value as 4.0 here there is no need to alter the value
(1.7,2.7,3.7,4.7,.... etc ) as to be represented as(1.5,2.5,3.5,4.5,.. etc )
so how to write an function for this where if the vale contains(1.7,2.7) i should change to 1.5,2.5
or if it contains 1.0,2.0 then there is no need to replace any value?
This extension method ought to do the job:
public decimal RoundToNearestHalf(this decimal value)
{
return Math.Round(value * 2) / 2;
}
var num1 = (3.7).RoundToNearestHalf(); // 3.5
var num1 = (4.0).RoundToNearestHalf(); // 4.0
I've used the decimal type in the code because it seems you want to maintain base 10 precision. If you don't, then float/double would do just as well, of course.
Use the DateTime type. Subtracting DateTime types returns a TimeSpan. Use TimeSpan.TotalHours to get your result. E.g.:-
var x = DateTime.Parse("12:30");
var y = DateTime.Parse("16:00");
Console.WriteLine((y - x).TotalHours);
Use DateTime type to work with time. Example:
string time1 = "12:30";
string time2 = "16:00";
TimeSpan diff = DateTime.Parse(time2)-DateTime.Parse(time2);
string diffString = diff.ToString("hh:mm"); // will be 03:30
Multiply hours with 60 and add minutes. You'll get total number of minutes.
12hours and 30 minutes = 720 + 30 = 750 minutes.
16 hours = 960 minutes.
Subtract the first value from the other and divide it by 60
(960 - 750) / 60 = 210 / 60 = 3.5
You should use TimeSpan and round it off:
TimeSpan startTime = new TimeSpan(12, 30, 0);
TimeSpan endTime = new TimeSpan(16, 0, 0);
TimeSpan span = endTime - startTime;
double totalHours = span.TotalHours;
double roundedToHalf = Math.Round(totalHours * 2) / 2;
Console.WriteLine(roundedToHalf);
UPDATE:
If the start and end time are from different dates, you should use DateTime for startTime and endTime.
If the values in your question represent times you can't do decimal arithmetic with them and expect time values as results.
You need to manipulate the values as times
I don't know C#, but it must have some time functions.
Have the times as DateTime then use Timspan to find the difference between the two times?
Times are not integers or floats. You can't work with them as if they are - you wouldn't try to do integer math using the String class, would you?
DateTime and TimeSpan are you friends for this kind of data manipulation.
You can use the C# Floor and Ceil method of the Math Class. Read more about it in the below URLs:
http://msdn.microsoft.com/en-us/library/system.math.ceiling(VS.71).aspx
http://dotnetperls.com/math-floor
string i = "2.0";
if (i == "2.3" || i == "3.3" || i == "4.3")
{
string strReplace = i.Replace(".3", ".5");
}
else
{
string strReplace = i;
}
I have a minute value and i want to have to 2 string values one with how many hours and the other with the minutes, e.g.:
Value - 121 minutes
string hours = 2
string minutes = 1
Value - 58 minutes
string hours = 0
string minutes = 58
How can I work this out in C#?
var span = System.TimeSpan.FromMinutes(121);
var hours = ((int)span.TotalHours).ToString();
var minutes = span.Minutes.ToString();
The ToString() is because you asked for string values ...
TotalHours are the complete hours in the TimeSpan, they can be more than 24 (whereas the "Hours" field has a maximum of 24)
Oh, and on second thought: Why use the TimeSpan and not calculate it yourself? Because TimeSpan is already there debugged & tested by Microsoft, it has a nice clean interface (looking at the code you easily see whats going on without having to follow a calculation mentally) and it easily extends to further solutions. (Have the input in seconds? Use TimeSpan.FromSeconds(). Want the days? Use span.TotalDays ...)
Update:
I just noticed mistake in my answer: TotalHours returns a fractional value of all the hours, so we have to truncate it to an integer before converting it to a string.
Use a Timespan struct and its Parse method.
int value = 121;
int hours = value / 60; // 2
int minutes = value % 60; // 1
string strHours = hours.ToString();
string strMinutes = minutes.ToString();
int value = 121;
int hours = value / 60;
int minutes = value % 60;
int value = 121;
TimeSpan timeSpan = TimeSpan.FromMinutes(value);
// gives you the rounded down value of 2
int hours = timeSpan.Hours;
// gives you the minutes left of the hour
int minutes = value - (hours * 60);