tags:

views:

171

answers:

4

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
+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
Seconds is not the same as TotalSeconds.
Ondrej Tucny
I posted and edited there and then. :) Thanks for pointing out though.
Yogesh
+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
+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