I want to compare two times in C# and want to make sure that the end time is later than the start time. The following is my code.
string startTime = "02:25 PM";
string endTime = "02:30 PM";
TimeSpan startTime = TimeSpan.Parse(StartTime);
TimeSpan endTime = TimeSpan.Parse(EndTime);
int timeDifference = startTime.CompareTo(endTime);
if (timeDifference.Equals(0) || timeDifference.Equals(-1))
{
errMessage.Append("The end time has to be greater than the start time. <br />");
}
The above code doesn't work as TimeSpan.Parse() throws an error as it can't handle the "PM" in the time value.
CodePudding user response:
If you want to do it with TimeSpans you'll have to handle the PM:
TimeSpan startTime = TimeSpan.Parse(StartTime.Remove(5));
TimeSpan endTime = TimeSpan.Parse(EndTime.Remove(5));
if(StartTime.Contains("PM"))
startTime = startTime TimeSpan.FromHours(12);
if(EndTime.Contains("PM"))
endTime = endTime TimeSpan.FromHours(12);
If your PM will vary in case, use an overload of Contains that can be case insens
Or you can get DateTime to do your parsing:
var startTime = DateTime.ParseExact(StartTime, "hh:mm tt", CultureInfo.InvariantCulture).TimeOfDay;
var endTime = DateTime.ParseExact(EndTime, "hh:mm tt", CultureInfo.InvariantCulture).TimeOfDay;
TimeSpans are a lot like numbers and are hence comparable with things like <
, >=
etc so you can just do:
if(startTime < endTime)
errMessage.Append("The end time has to be greater than the start time. <br />");