Reputation: 10354
I have two string variables such as StartTime and EndTime. I need to Calculate the TotalTime by subtracting the EndTime with StartTime.
The Format of StartTime and EndTime is as like follows:
StartTime = "08:00 AM";
EndTime = "04:00 PM";
TotalTime in Hours and Mins Format. How to calculate this using C#?
Upvotes: 1
Views: 18984
Reputation: 48568
Convert them to DateTime
and substract one from other to get TimeSpan
.
DateTime StartTime = DateTime.Parse("08:00 AM");
DateTime EndTime = DateTime.Parse("04:00 PM"); // It converts this to 1600.
TimeSpan ts = EndTime - StartTime;
When i run above code it is giving me
ts.Days // 0
ts.Hours // 8
ts.Milliseconds // 0
ts.Minutes // 0
ts.Seconds // 0
ts.Ticks // 288000000000
ts.TotalDays // 0.3333333333333333331
ts.TotalHours // 8.0
ts.TotalMilliseconds // 28800000.0
ts.TotalMinutes // 480.0
ts.TotalSeconds // 28800.0
to get what you want.
Upvotes: 8
Reputation: 700362
Use the ParseExact
method to specify the exact format when you parse the strings to DateTime
values, then subtract them to get a TimeSpan
value:
string StartTime = "08:00 AM";
string EndTime = "04:00 PM";
DateTime start = DateTime.ParseExact(StartTime, "hh:mm tt", CultureInfo.InvariantCulture);
DateTime end = DateTime.ParseExact(EndTime, "hh:mm tt", CultureInfo.InvariantCulture);
TimeSpan diff = end - start;
Console.WriteLine(diff.TotalMinutes);
Output:
480
Upvotes: 3
Reputation: 5100
You should convert your strings to DateTime
and use TimeSpan
to calculate the difference
DateTime d1 = DateTime.Parse(StartTime);
DateTime d2 = DateTime.Parse(EndTime);
TimeSpan ts = dt.Subtract(dt2);
Something like the above. You might need ParseExact
instead of Parse
For your sample times, ts.ToString()
will return a string "08:00:00"
giving hours, minutes and seconds difference
Upvotes: 6
Reputation: 12874
string StartTime, EndTime;
StartTime = "08:00 AM";
EndTime = "04:00 PM";
DateTime startTime = DateTime.Parse(StartTime);
DateTime endTime = DateTime.Parse(EndTime);
TimeSpan ts = endTime.Subtract(startTime);
Output : 08:00:00 The put is in Hrs:Min:Sec format.
thats What you needed. Right
Note: endTime should come first while subtracting.
Upvotes: 2