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:
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:
- get current Unix timestamp
- transform the retrieved timestamp to a date
- subtract 1 day from the date
- transform the timestamp to test to a date
- 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"