Calculate seconds between two dates / times in YYYY-MM-DDH: MM: SSZ format
Is there a quick way (in C #) to calculate the number of seconds between two strings containing a date / time in the format YYYY-MM-DDTG: MM: SSZ.
For example:
string startTime = "2017-03-27T13:58:39Z";
string endTime = "2017-03-27T14:07:26Z";
int numSecs = calculateSecondsBetween(startTime, endTime);
Yes, I could create a function that parses all of this, but I was hoping for something simpler.
+3
source to share
3 answers
Subtract the time and get TotalSeconds
:
string startTime = "2017-03-27T13:58:39Z";
string endTime = "2017-03-27T14:07:26Z";
DateTime startTimeDt = Convert.ToDateTime(startTime);
DateTime endTimeDt = Convert.ToDateTime(endTime);
var diffInSeconds = (endTimeDt - startTimeDt).TotalSeconds;
Console.Write(diffInSeconds);
Hope it helps!
+4
source to share
fubo and mindOfAi got there much faster than me, but if you paste your code after something convenient and quick, you can create an extension method to make it cleaner:
public static class DateTimeExtensions
{
public static int NumberOfSecondsUntil(this string start, string end)
{
return (int)(DateTime.Parse(end) - DateTime.Parse(start)).TotalSeconds;
}
}
It can then be called like this:
int numSecs = startTime.NumberOfSecondsUntil(endTime);
YMMV :)
0
source to share