I get from TimeSpan.TotalHours 24,75 hours.
How can I convert this to get the full and not roundes hours (=24) plus the minutes (0,75hours = 45 minutes)? So the result should be hours = 24 and minutes = 45
I tried to convert it to string and make substring but I would like to know if there is a better way than this.
string test = Reststunden.TotalHours.ToString().Substring(Reststunden.TotalHours.ToString().IndexOf(","),3).Replace(",", "");
double Minuten = Convert.ToInt16(test) * 0.6;
Well just round the total hours appropriately by casting, and then use the Minutes property:
int hours = (int) timeSpan.TotalHours;
int minutes = timeSpan.Minutes;
If you'll ever have a negative TimeSpan, you should think about what you want the results to be and add appropriate tests - you may well find it doesn't do what you want with the simple code above.
How about:
var ts = TimeSpan.FromHours(24.75);
var h = System.Math.Floor(ts.TotalHours);
var m = (ts.TotalHours - h) * 60;
Or even:
var h = (int) (ts.TotalMinutes / 60);
var m = ts.TotalMinutes % 60;
I needed to display the total hours and minutes in the following format HH:mm.
With the help of the other answers I came to the following result:
var end = DateTime.Now;
var duration = end - StartUpTime;
var h = (int)(duration.TotalMinutes / 60);
var m = (int)(duration.TotalMinutes % 60);
var text = $"{h:D2}:{m:D2}";
Related
I have two times like 100:45 and 395:50
I need to find the subtraction and addition between these two times in the asp.net web application
I will expect like this 100:45+395:50=496:35 and 100:45-395:50=295:05
assuming the times are given in a string. then you can split the times to get the equivalent minutes. now it becomes a simple mathematics problem and now perform addition and subtraction accordingly.
string time = "100:45";
string[] parts = time.Split(':');
int hours = int.Parse(parts[0]);
int minutes = int.Parse(parts[1]);
int totalMinutes = hours * 60 + minutes;
so for your case
int mins1 = 100 * 60 + 45;
int mins2 = 395 * 60 + 50;
int totalMinutes = mins1 + mins2;
int totalHours = totalMinutes / 60;
int remainingMinutes = totalMinutes % 60;
string sum = $"{totalHours}:{remainingMinutes}";
use the same concept to get the subtraction as well.
You can convert times to TimeSpan.FromMinutes and to get the desired output using TimeSpan.TotalHours and TimeSpan.Minutes
string s1 = "100:45";
string s2 = "395:50";
TimeSpan spWorkMin = TimeSpan.FromMinutes(int.Parse(s1.Split(':')[0]) * 60 +
int.Parse(s2.Split(':')[0]) * 60 +
int.Parse(s1.Split(':')[1]) +
int.Parse(s2.Split(':')[1]));
var sum =string.Format("{0:00}:{1:00}", (int)tSum.TotalHours, tSum.Minutes);//496:35
TimeSpan tsub = TimeSpan.FromMinutes(int.Parse(s1.Split(':')[0]) * 60 -
int.Parse(s2.Split(':')[0]) * 60 +
int.Parse(s1.Split(':')[1]) -
int.Parse(s2.Split(':')[1]));
var subtract = string.Format("{0:00}:{1:00}", Math.Abs((int)tsub.TotalHours),Math.Abs(tsub.Minutes)); //295:05
TimeSpan do the trick
TimeSpan ts1 = new TimeSpan(0, 100, 45);
TimeSpan ts2 = new TimeSpan(0, 395, 50);
var tsResult = ts1 + ts2;
string outPut = string.Format("{0}:{1}", Math.Floor(tsResult.TotalMinutes), tsResult.Seconds);
I have to do the sum of more time spans in a DataTable to use the code below, but the total sum is wrong, what is due to this:
DataTable(dt) values:
09:21
08:28
08:46
04:23
Total hours: 30,97 //97 minutes is not correct
C# Code:
TimeSpan totaleOreMarcaTempo = TimeSpan.Zero;
int conta = 0;
foreach (DataRow dr in dt.Rows)
{
String OreMarcaTempo = tm.ConteggioOreGiornaliere(dr["Data"].ToString()); //This string contains at each cycle 09:21 08:28 08:46 04:23
TimeSpan oreMarcatempo = TimeSpan.Parse(OreMarcaTempo.ToString());
totaleOreMarcaTempo = totaleOreMarcaTempo + oreMarcatempo;
conta++;
}
labelTotaleOreMarcaTempoMod.Text = "" + (int)totaleOreMarcaTempo.TotalHours + ":" + totaleOreMarcaTempo.Minutes.ToString(); //30:58
30.97 is the correct number of hours. It does not mean "30 hours and 97 minutes".
30.97 hours is 30 hours and 58 minutes. 58 / 60 is roughly 0.97.
I think you just need to format your string properly. One way to format it is:
#"{(int)yourTimeSpan.TotalHours}:{yourTimeSpan.Minutes}"
Value 30.97 is correct (30.97 hours, where 0.97 is hour (60 minutes * 0.97 = 58 minutes),
you just need convert fraction of TotalHours to minutes.
var raw = "09:21 08:28 08:46 04:23";
var totalTimespan =
raw.Split(" ")
.Select(TimeSpan.Parse)
.Aggregate(TimeSpan.Zero, (total, span) => total += span);
// Use integer value of TotalHours
var hours = (int)totalTimespan.TotalHours;
// Use actual minutes
var minutes = totalTimespan.Minutes
var output = $"{hours}:{minutes}";
var expected = "30:58";
output.Should().Be(expected); // Pass Ok
You have to change the Format. 0,98 hours = 58,2 minutes
labelTotaleOreMarcaTempoMod.Text =string.Format ("{0:00}:{1:00}:{2:00}",
(int)totaleOreMarcaTempo.TotalHours,
totaleOreMarcaTempo.Minutes,
totaleOreMarcaTempo.Seconds);
To print out a TimeSpan "correctly", just use the correct formatting:
labelTotaleOreMarcaTempoMod.Text = totaleOreMarcaTempo.ToString("c");
or
labelTotaleOreMarcaTempoMod.Text = totaleOreMarcaTempo.ToString("hh':'mm");
EDIT Do note (thanks, Basin) that the second form ignores days.
Reference: Standard TimeSpan Format Strings and Custom TimeSpan Format Strings
30.97 is the correct value but not HH:mm format.
For me the correct solution is :
var total = Math.Floor( totaleOreMarcaTempo.TotalMinutes / 60).ToString() + ":" + Math.Floor( totaleOreMarcaTempo.TotalMinutes % 60).ToString();
I have the sum of the working duration of Employees in a specific period. I need to convert this Working Duration into days, hours and minutes. The problem is my day is equal to 9 Hours, not 24 Hours. Means I am dividing my Duration with 9. But the result I am getting is in points and I can't convert to my yearning format. Following is my code:
var Durations = TimeSpan.FromMinutes(db.Attendances.Where(x => x.EmployeeId == id)
.Sum(x => TimeSpan.Parse(x.Duration).TotalMinutes));
var TotalDuration = string.Format("{0}:{1}", Durations.TotalHours, Durations.Minutes);
This one is working absolutely fine. I am getting results in the following format:
H:M
8:5
12:7
19:15
The problem is I need to convert hours into Days and Hours when I divide it by 9. E.g. 19. If I divide 19 by 9 I get 2.111111 Means 2 Days and 1 Hour. How can I get the answer in days and hours format?
I think this should answer your question:
TimeSpan s = new TimeSpan(20,0, 0);
int day = (int)s.TotalHours / 9;
int hour = (int)s.TotalHours % 9;
Console.WriteLine($"the duration in day is {day } hour {hour}");
You can add an extension method to TimeSpan.
public static (int day,int hour) GetDayAndHour(this TimeSpan timeSpan,int dayDuration == 9) {
var number= timeSpan.TotalHours/dayDuration;
int day = (int)Math.Truncate(number);
int hour= (int)Math.Truncate((number-day)*10);
return (day,hour);
}
I use C#7 tuple.If you use previous version, create costume datatype or use Tuple<int, int>.
int totalmins = 5000; // given input
int hourPerDay = 9 // given input
int dayHour = 60 * hourPerDay;
int days = totalmins / dayHour;
int hours = (totalmins % dayHour) / 60;
int mins = tot_mins % 60;
const double PERCENT = 0.25;
DateTime t1 = Convert.ToDateTime(txtB_StartT.Text);
DateTime t2 = Convert.ToDateTime(txtB_EndT.Text);
TimeSpan ts = t1.Subtract(t2);
I cant seem to get this to parse into a DateTime
double tsMin = Convert.ToDouble(ts);
double tsMinTot = ts.TotalMinutes;
short tsMinPercent = (short)(((double)tsMinTot) * PERCENT);
double tsAndPercentTot = tsMinPercent + tsMinTot;
My goal here was to find a timediff, find what 25% of that timediff is and add it to the timediff.
DateTime newTimeMinTot = Convert.ToDateTime(tsAndPercentTot);
int hours = newTimeMinTot.Hour;
int minutes = newTimeMinTot.Minute;
An attempt to get a calculated new Datetime
string newTimeStrg = string.Format("{0:d1}:{1:d2}", hours, minutes);
txtB_NewDelivT.Text = newTimeStrg;
Attempt to output new DateTime to TextBox.
Someone please explain. How can I make the user input in military time and make this work.
Do it like this:
const double PERCENT = 0.25;
DateTime t1 = Convert.ToDateTime(txtB_StartT.Text);
DateTime t2 = Convert.ToDateTime(txtB_EndT.Text);
TimeSpan ts = t1.Subtract(t2);
long tsMinPercent = ts.Ticks + (long)(ts.Ticks * PERCENT);
var tsAndPercentTot = TimeSpan.FromTicks(tsMinPercent);
string newTimeStrg = string.Format("{0:d1}:{1:d2}", tsAndPercentTot.Hours, tsAndPercentTot.Minutes);
txtB_NewDelivT.Text = newTimeStrg;
Here I am using DateTime.Ticks to calculate percentage of time of difference and TimeSpan.FromTicks to find DateTime again from calculated percentage DateTime.
Instead using TextBox you can use TimePicker.
to force your date/datetime format
DateTime mydate = DateTime.ParseExact(TextBox1.Text.Trim(), "dd/MM/yyyy", null);
Based on your comment where you write that the input values are "0945" and "1445", I suggest you to replace your TextBox controls with DateTimePicker controls.
Just to have them display values as you are doing right now, you'll have to set some properties as I show you here.
picker.Format = DateTimePickerFormat.Custom;
picker.CustomFormat = "HHmm";
picker.ShowUpDown = true;
later, the picker.Value will return a whole date with time, where minutes and seconds will resemble the input values.
You can obvously set the properties' values from the designer.
Regards,
Daniele.
Since I don't have your form, I'll leave out the UI interaction. Here's how you can parse an input stream. I've show how to parse a hh:mm format, as well as a hhmm format:
var start = TimeSpan.ParseExact("10:00", "hh\\:mm", CultureInfo.InvariantCulture);
var finish = TimeSpan.ParseExact("1100", "hhmm", CultureInfo.InvariantCulture);
Once you have the start and finish, all we have to do is the math. We'll create a new TimeSpan from the ticks (the smallest unit of measurement on a TimeSpan) multiplied by our percentage (0.25). Then we just add the adjustment to our start time and we're done! You can then assign that into where ever you need the output.
var diff = finish - start;
var adjustment = TimeSpan.FromTicks((long)(diff.Ticks * 0.25));
var adjustedStart = start + adjustment;
You can run the code out at dotNetFiddle. I've included output there so you can see the intermediate results along the way.
Ok well i took a different approach and it worked out fairly easy.
I'm not sure if I'm allowed to answer my own question but i figure it
will help someone with the same issue i had.
// Set Constant values.
const double PERCENT = .25;
const int HUN_PART = 100, SIXTY = 60, one = 1;
// Parse start time textbox value as int
// Calculate start time hours and minutes
int sT = int.Parse(textBox1.Text);
int sH = sT / HUN_PART;
int sM = sT % HUN_PART;
// Calculate total start time in minutes
int sH_M = sH * SIXTY;
int sTotM = sH_M + sM;
// Parse end time textbox value as int
// Calculate end time hours and minutes
int eT = int.Parse(textBox2.Text);
int eH = eT / HUN_PART;
int eM = eT % HUN_PART;
// Calculate total end time in minutes
int eH_M = eH * SIXTY;
int eTotM = eH_M + eM;
// Calculate time difference in minutea
// Calculate percent of time difference
double dT_M = Convert.ToInt32(eTotM - sTotM);
int perc = Convert.ToInt32(dT_M * PERCENT);
// Calculate new arrival time in total min then in hours
double newD_M = perc + eTotM;
double newD_H = newD_M / SIXTY;
// Calculate new arrivaltime in remaining minutes
double nD_H_Convert = Math.Truncate(newD_H);
int nD_H = Convert.ToInt32(nD_H_Convert);
int nD_Hours = nD_H * HUN_PART;
double nD_Min = nD_H * SIXTY;
int nD_M = Convert.ToInt32(newD_M - nD_Min);
int newDeliveryTime = (nD_H * HUN_PART) + nD_M;
// Put values for new arive time hours and minutes in appropriate string format
string newTime = string.Format("{0:d4}", newDeliveryTime);
// Output arrival time string in textbox
textBox3.Text = newTime;
I was apparently trying to do more than was actually required, so by using a few simple calculations the issue was resolved.
Thank you for the help everyone.
How do I convert a TimeSpan to a float , taking into account all of the processing unit (hour minute) for example
if (unit = hour)
convert TimeSpan to a float hours
In another context, is there not a data type "Timespan" in SQL Server ?
Use the Total* properties on TimeSpan, e.g. TimeSpan.TotalHours.
Example for minutes:
var t = new TimeSpan();
var total = t.TotalMinutes;
You can do something like this
TimeSpan elapsedTime = new TimeSpan(125000);
float floatTimeSpan;
int seconds, milliseconds;
seconds = elapsedTime.Seconds;
milliseconds = elapsedTime.Milliseconds;
floatTimeSpan = (float)seconds + ((float)milliseconds / 1000);
Console.WriteLine("Time Span: {0}", floatTimeSpan);
The program output looks like this:
Time Span: 0.012
internal static string TimeSpanToDouble(TimeSpan timeSpan, string unit)
{
double result = 0;
if (unit.Equals("MINUTES"))
result = timeSpan.TotalMinutes;
else if (unit.Equals("HOURS"))
result = timeSpan.TotalHours;
else if (unit.Equals("DAYS"))
result = timeSpan.TotalHours / 24;
else
throw new Exception();
return Convert.ToString(result);
}
You can use Convert.ToSingle, like this:
var ts = new Timespan(0, 1, 1, 30);
var minutes = Convert.ToSingle(ts.TotalMinutes);
var hours = Convert.ToSingle(ts.TotalHours);
The resulting minutes and hours will be, respectively, 61.5 and 1.025
Check out this dotnetfiddle: https://dotnetfiddle.net/uSQfk0
double TsToHoursDouble(TimeSpan ts) => ts.TotalMinutes / 60;
double TsToMinsDouble(TimeSpan ts) => ts.TotalMinutes;
using:
var hrs = TsToHoursDouble(someTimeSpan);
if you need more accurate results, you can use TotalSeconds in such calculations