Reputation: 3091
How to compare two DateTime to seconds?
Upvotes: 32
Views: 34358
Reputation: 1483
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.
Upvotes: 3
Reputation: 1500065
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.
Upvotes: 39
Reputation: 14608
If you subtract one date from another, it returns a TimeSpan
which has a TotalSeconds
property. So:
double seconds = (Date1 - Date2).TotalSeconds;
Upvotes: 18
Reputation: 268225
var date1 = DateTime.Now;
var date2 = new DateTime (1992, 6, 6);
var seconds = (date1 - date2).TotalSeconds;
Upvotes: 45