Skip to content Skip to sidebar Skip to footer

Elegantly Check If A Given Date Is Yesterday

Assuming you have a Unix timestamp, what would be an easy and/or elegant way to check if that timestamp was some time yesterday? I am mostly looking for solutions in Javascript, PH

Solution 1:

In C# you could use this:

bool isYesterday = DateTime.Today - time.Date == TimeSpan.FromDays(1);

Solution 2:

PHP:

$isYesterday = date('Ymd', $timestamp) == date('Ymd', strtotime('yesterday'));

Solution 3:

You can use this in C#:

bool isYesterday = (dateToCheck.Date.AddDays(1) == DateTime.Now.Date);

Solution 4:

In pseudo code, to compare timestamps:

  1. get current Unix timestamp
  2. transform the retrieved timestamp to a date
  3. subtract 1 day from the date
  4. transform the timestamp to test to a date
  5. compare both dates. If they're equal the tested timestamp was yesterday.

Watch out for timezones if you show the results to a user. For me it's now 13:39 on July 9 2010. A timestamp for 14 hours ago for me is yesterday. But for someone in a different timezone where it's now 15:39, 14 hours ago wasn't yesterday!

Another problem might be systems with a wrong time/date setup. For example if you use JavaScript and the system time of the visitors PC is wrong, the program may come to a wrong conclusion. If it's essential to get a correct answer, retrieve the current time from a known source with a correct time.

Solution 5:

An example in Smalltalk using Pharo/Squeak

(Dateyear: 2014month: 4day: 24) =Date yesterday

Post a Comment for "Elegantly Check If A Given Date Is Yesterday"