Calculate total number of Hours asp.net c# - c#

I have done the following piece of code to add the Hours and thus calculate total number of hours.
string hour1="48.40";
string hour2 = "45.35";
TimeSpan ts = new TimeSpan(int.Parse(hour1.Split('.')[0]),int.Parse(hour1.Split('.')[1]),
0);
TimeSpan ts1 = new TimeSpan(int.Parse(hour2.Split('.')[0]),int.Parse(hour2.Split('.')[1]),
0);
Double total = (ts.TotalHours) + (ts1.TotalHours);
The problem here is when i add hour1 and hour2 the total comes as 64.25 which actually should have been 64.15
This is just one of the test case, if i put hour1= 40.00 and hour2= 40.10 than the value in the total comes as 80.166666666666657 which actually should have been 80.10
can anyone help me understand what am i doing wrong and what is the correct way to add HOUR and get total number of hours ?

Actually you're getting correct result - just mixing minutes and fractional parts of hours.
80 hrs 10 mins is 80 1/6 hours
64 hours 15 mins is 64 1/4 hours

It gets a little strange when you have timestamps put into strings. But if you need to do it like this, this code should work
string hour1="48.40";
string hour2 = "45.35";
//find total number of minutes for each hour above
int minutes1 = int.Parse(hour1.Split('.')[0])*60+int.Parse(hour1.Split('.')[1]);
int minutes2 = int.Parse(hour2.Split('.')[0])*60+int.Parse(hour2.Split('.')[1]);
//calculate back to hours and minutes and reassemble as a string
string result = (minutes1+minutes2)/60+"."+(minutes1+minutes2)%60;
And I hope you are expecting 94.15 and not 64.15 in your example above.

You may use next code to get result you would like to:
string hour1 = "48.40";
string hour2 = "45.35";
TimeSpan ts = new TimeSpan(int.Parse(hour1.Split('.')[0]), int.Parse(hour1.Split('.')[1]),
0);
TimeSpan ts1 = new TimeSpan(int.Parse(hour2.Split('.')[0]), int.Parse(hour2.Split('.')[1]),
0);
TimeSpan total = ts + ts1;
int hours = (int)total.TotalHours;
int minutes = total.Minutes;

Related

How to subtract time (HHH:MM)

I want to Subtract two time strings that I read from an excel sheet, for example 150:24 and 124:30.
The time format is HHH:MM in the excel sheet. How can I subtract these two strings in C#?
I can not illustrate the data format! also I can not write true code for this issue.
You can calculate the times difference based on minutes. Then convert to any format you want...
var s1 = "150:24".Split(':');
var s2 = "124:30".Split(':');
var diffMinutes= int.Parse(s1[0]) * 60 + int.Parse(s1[1]) - int.Parse(s2[0]) * 60 - int.Parse(s2[1]);
Console.WriteLine("difference in minutes: " +diffMinutes);
//difference in minutes: 1554
Console.WriteLine("difference in HHH:MM: "+ diffMinutes/60 + ":"+diffMinutes%60);
//difference in HHH:MM: 25:54
TimeSpan t= TimeSpan.FromMinutes(result);
Console.WriteLine(t);
//1.01:54:00
TimeSpan.Parse unfortunately does not work is the hour part is > 23. But of course it is possible to split on the ':', convert the hour and minute parts to integers separately and construct a TimeSpan from it:
public static TimeSpan ParseHoursAndMinutes(string s)
{
// NOTE: no error checking!
var parts = s.Split(':');
var hours = int.Parse(parts[0]);
var minutes = int.Parse(parts[1]);
return new TimeSpan(hours, minutes, 0);
}
var diff = ParseHoursAndMinutes("150:24") - ParseHoursAndMinutes("124:30");
Console.WriteLine(diff); // => 1.01:54:00

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 ?
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}"

c# TimeSpan Converting Minutes to Hours

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}");

Calculation of Total seconds from a particular format of time

How to calculate total seconds of '33 hr 40 mins 40 secs' in asp.net c#
new TimeSpan(33, 40, 40).TotalSeconds;
If you're given a string of the format "33 hr 40 mins 40 secs", you'll have to parse the string first.
var s = "33 hr 40 mins 40 secs";
var matches = Regex.Matches(s, "\d+");
var hr = Convert.ToInt32(matches[0]);
var min = Convert.ToInt32(matches[1]);
var sec = Convert.ToInt32(matches[2]);
var totalSec = hr * 3600 + min * 60 + sec;
That code, obviously, has no error checking involved. So you might want to do things like make sure that 3 matches were found, that the matches are valid values for minutes and seconds, etc.
Separate hour, minute and seconds and then use
Edited
TimeSpan ts = new TimeSpan(33,40,40);
/* Gets the value of the current TimeSpan structure expressed in whole
and fractional seconds. */
double totalSeconds = ts.TotalSeconds;
Read TimeSpan.TotalSeconds Property
Try this -
// Calculate seconds in string of format "xx hr yy mins zz secs"
public double TotalSecs(string myTime)
{
// Split the string into an array
string[] myTimeArr = myTime.Split(' ');
// Calc and return the total seconds
return new TimeSpan(Convert.ToInt32(myTimeArr[0]),
Convert.ToInt32(myTimeArr[2]),
Convert.ToInt32(myTimeArr[4])).TotalSeconds;
}

Work out min and hours

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);

Categories

Resources