How to compare two DateTime to seconds?
+18
A:
var date1 = DateTime.Now;
var date2 = new DateTime (1992, 6, 6);
var seconds = (date1 - date2).TotalSeconds;
gaearon
2010-09-28 19:07:35
+7
A:
If you subtract one date from another, it returns a TimeSpan
which has a TotalSeconds
property. So:
double seconds = (Date1 - Date2).TotalSeconds;
Yogesh
2010-09-28 19:07:43
Seconds is not the same as TotalSeconds.
Ondrej Tucny
2010-09-28 19:09:15
I posted and edited there and then. :) Thanks for pointing out though.
Yogesh
2010-09-28 19:10:05
+1
A:
Do you mean comparing two DateTime
values down to the second? If so, you might want something like:
private static DateTime RoundToSecond(DateTime dt)
{
return new DateTime(dt.Year, dt.Month, dt.Day,
dt.Hour, dt.Minute, dt.Second);
}
...
if (RoundToSecond(dt1) == RoundToSecond(dt2))
{
...
}
Alternatively, to find out whether the two DateTimes are within a second of each other:
if (Math.Abs((dt1 - dt2).TotalSeconds) <= 1)
If neither of these help, please give more detail in the question.
Jon Skeet
2010-09-28 19:09:07
+1
A:
DateTime start = DateTime.now;
DateTime end = DateTime.end;
TimeSpan dif = end - start;
dif will be of the form 0:0:0:0 where the third value is seconds.
Prof Plum
2010-09-28 19:26:02