I have a series of times that are coming to me as strings from a web service. The times are formated as HH:MM:SS:000 (3 milisecond digits). I need to compare two times to determine if one is more than twice as long as the other:
if ( timeA / timeB > 2 )
What's the simplest way to work with the time strings?
If I was writing in Python this would be the answer to my question: Difference between two time intervals?
(Except the operator I need is division, not subtraction)
Edit: What I'm really looking for is a way to get the ratio of timeA to timeB, which requires division, not subtraction. Unfortunately, the DateTime structure doesn't appear to have a division operator. Updated the question title and body to reflect this.
Solution:
Based on the answer I picked below, which was the simplest of all the proposed methods so far, here is the working solution:
DateTime timeA;
DateTime timeB;
DateTime.TryParse(webServiceTimeString_A, out timeA);
DateTime.TryParse(webServiceTimeString_B, out timeB);
// TimeA is more than twice the duration of TimeB.
if ( (double)timeA.TimeOfDay.Ticks / (double)timeB.TimeOfDay.Ticks > 2.0f )
{
// Do stuff.
}
else
{
// Do different stuff.
}
JavaScript:
Recently, this functionality was also required in JavaScript for an AJAX call, so, I had to write a conversion function after all (just not in C#). In case it's needed:
if (_timeInSeconds(timeA) / _timeInSeconds(timeB) > 2) {
// Do stuff.
}
// Convert HH:MM:SS:000 string to a number of seconds so we can do math on it.
function _timeInSeconds(stringTime) {
var timeArray = stringTime.split(":");
var timeInSeconds = 0;
//HH
timeInSeconds += (parseInt(timeArray[0], 10) * 3600);
//MM
timeInSeconds += (parseInt(timeArray[1], 10) * 60);
//SS
timeInSeconds += (parseInt(timeArray[2], 10));
//Milliseconds
timeInSeconds += (parseInt(timeArray[3], 10) / 1000);
return timeInSeconds;
}
Word to the wise: Make sure to specify the second argument of parseInt...
parseInt(string, 10)
...to specify that the string is a Base-10 number. Otherwise, if the string starts with 0
(common in HH:MM:SS formats), JavaScript decides it's a Base-8 number. This causes the strings "08"
and "09"
to be converted to decimal integer 0
(because 8 and 9 don't exist in Base-8), and the calculations get thrown off.