Currently I am doing this to take the difference in days for two timestamps
function getDifferenceInDaysTillNow($timestamp) {
try {
$streakLastAwardedAtDateTime = DateTime::createFromFormat('U', $timestamp);
$streakLastAwardedAtDateTime->setTimezone(new DateTimeZone('Asia/Kolkata'));
$nowDateTime = new DateTime();
$nowDateTime->setTimezone(new DateTimeZone('Asia/Kolkata'));
$diff = $streakLastAwardedAtDateTime->diff($nowDateTime);
return $diff->format('%a');
}catch(Exception $e) {
throw new Exception($e);
}
}
PHP Fiddle for the above approach
This gives a difference of 1
(1day) if the timestamps have 24hours difference.
But I just want to know if a timestamp lies in the previous day.
For example it can just be a difference of 2hours
or 6hours
doesn’t matter.
I want to return a Boolean (true or false) telling if the provided timestamp lies in the previousDay or not.
Any help is appriciated.
Thank you.
2
Answers
For this, you can simply check if the
y
orm
property is greater than 0. If yes, return false. If thed
difference is greater than 1, then also we need to return false since the difference is more than 1 day.Additional check is to make sure the timestamp isn’t the same day as today.
Online Demo
A DateTime object is created from the timestamp, then converted to the correct time zone with setTimeZone and the time is set to 00:00. Then it can be compared directly with ‘yesterday’.