Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing DateTime objects

Tags:

c#

timestamp

Goal - find out which DateTime is more recent.

Can I figure this out with this code:

DateTime dt1 = new DateTime(...); //let's say it was created on 1/1/2000

DateTime dt2 = new DateTime(...); //let's say it was create on 1/1/2011 

if (dt2.ToBinary() > dt1.ToBinary()) {
print dt2 is newer than dt1 }

Can I simply convert the DateTime objects to binary, then presume that the larger one is more recent?

Thanks, Kevin

like image 664
Kevin Meredith Avatar asked Jan 25 '26 07:01

Kevin Meredith


2 Answers

if (dt2 > dt1) {
print dt2 is newer than dt1 }

should be enough as DateTime overloads the comparison operators.

like image 192
Simon Mourier Avatar answered Jan 26 '26 20:01

Simon Mourier


You can usually do better than that:

if (dt2 > dt1)

The tricky bit is taking time zones into consideration... you can potentially use

if (dt2.ToUniversalTime() > dt1.ToUniversalTime())

but only if you know that any "local" times really are local in the system's time zone.

Dates and times in .NET are a bit of a mess :(

like image 28
Jon Skeet Avatar answered Jan 26 '26 19:01

Jon Skeet