I'm trying to calculate time elapsed (just hours and minutes) between start and end time. I'd like the string to be easy to enter, if possible. Don't really need the p.m. part.
https://dotnetfiddle.net/lWxVXK
Expecting:
1.5 hours
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
string startTime = "6:00 pm";
string endTime = "8:30 pm";
string format = "HH:mm";
TimeSpan startTimeSpan = TimeSpan.ParseExact(startTime, format, null);
TimeSpan endTimeSpan = TimeSpan.ParseExact(endTime, format, null);
TimeSpan result = startTimeSpan - endTimeSpan;
string elapsedTimeString = string.Format("{0}:{1}", result.Hours.ToString("00"), result.Minutes.ToString("00"));
Console.WriteLine(elapsedTimeString);
}
}
CodePudding user response:
You don't use AM and PM with TimeSpans
because they are meaningless. A TimeSpan
is a period of time. It has no start and no end, just a duration. It can be more than 24 hours, so how could AM and PM have meaning? If you want to enter times as a time of day using "h:mm tt" format then you need to parse them as DateTime
, not TimeSpan
. AM and PM do have meaning for DateTime
because it represents a point in time.
So, either enter your values using "HH:mm" format parse them as TimeSpans
or else enter them using "h:mm tt" format and parse them as DateTimes
. Either way will work as either subtraction will produce a TimeSpan
but you have to enter them and parse them using the same format and use the appropriate type based on that format.
Also, if you have read the relevant documentation (which you should have done) then you know that you need to escape a colon in a TimeSpan
format specifier where you don't in a DateTime
format specifier.
All that means that you should either do this:
string startTime = "18:00";
string endTime = "20:30";
string format = "HH\:mm";
TimeSpan startTimeSpan = TimeSpan.ParseExact(startTime, format, null);
TimeSpan endTimeSpan = TimeSpan.ParseExact(endTime, format, null);
or this:
string startTime = "6:00 pm";
string endTime = "8:30 pm";
string format = "h:mm tt";
DateTime startTimeSpan = DateTime.ParseExact(startTime, format, null);
DateTime endTimeSpan = DateTime.ParseExact(endTime, format, null);