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.
CodePudding user response:
For this, you can simply check if the y
or m
property is greater than 0. If yes, return false. If the d
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.
<?php
function getDifferenceInDaysTillNow($timestamp) {
try {
$streakLastAwardedAtDateTime = DateTime::createFromFormat('U', $timestamp);
$streakLastAwardedAtDateTime->setTimezone(new DateTimeZone('Asia/Kolkata'));
$nowDateTime = new DateTime();
$nowDateTime->setTimezone(new DateTimeZone('Asia/Kolkata'));
// check difference between lastStreakAward and now
$diff = $streakLastAwardedAtDateTime->diff($nowDateTime);
if($diff->y > 0 || $diff-> m > 0 || $diff->d > 1) return false;
return date("Y-m-d", $timestamp) != date("Y-m-d");
}catch(Exception $e) {
throw new Exception($e);
}
}
$timestamp = 1670211229; // Monday, 5 December 2022 09:03:49 GMT 05:30
var_dump(getDifferenceInDaysTillNow($timestamp));
CodePudding user response:
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'.
$timestamp = 1670211229; //5 December 2022 09:03:49
$timeZone = new DateTimeZone('Asia/Kolkata');
$date = date_create('@'.$timestamp)
->setTimeZone($timeZone)
->setTime(0,0,0,0)
;
$isTimeStampFromYesterday = ($date == date_create('yesterday',$timeZone));