Vlad Omelyanchuk
Vlad Omelyanchuk

Reputation: 3091

How to compare two DateTime to seconds?

How to compare two DateTime to seconds?

Upvotes: 32

Views: 34358

Answers (4)

Morgan Herlocker
Morgan Herlocker

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

Jon Skeet
Jon Skeet

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

Yogesh
Yogesh

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

Dan Abramov
Dan Abramov

Reputation: 268225

var date1 = DateTime.Now;
var date2 = new DateTime (1992, 6, 6);

var seconds = (date1 - date2).TotalSeconds;

Upvotes: 45

Related Questions