Search code examples
php-carbonlaravel-5.7

laravel carbon Compare two timezone times from timestamp


I want to compare timings of different timezones. Timestamp is stored in database using Mutators.My code is like below,

public function setScheduledOnAttribute($value)
{
    $this->attributes['scheduled_on'] = Carbon::parse($value)->timestamp;
}

public function getScheduledOnAttribute($value)
{
    return $value * 1000;
}

How can I compare current time with current time in Africa/Casablanca timezone.

Right now I am doing is

 $time = Carbon::now();
 $scheduleTime = Carbon::createFromTimestamp($scheduleTime['scheduled_on']/1000, 'Africa/Casablanca')->toDateTimeString();

Am I right? It is not satisfying condition

if ($time >= $scheduleTime) {
// some task
}

please suggest me..any help would be appreciated.


Solution

  • You don't need to parse it to a datetime String. If you keep it as a Carbon instance, it would be much easier to compare. Here are some examples:

    // First we create a new date/time in Dubai's timezone
    $dubai = \Carbon\Carbon::now(new DateTimeZone('Asia/Dubai'));
    
    echo "The date/time in Dubai is: {$dubai} \n";
    
    // We convert that date to Casablanca's timezone 
    $casablanca = \Carbon\Carbon::createFromTimestamp($dubai->timestamp, 'Africa/Casablanca'); 
    
    echo "The date/time in Casablanca is: {$casablanca} \n";
    
    // Let's create a date/time which is tomorrow in Zurich for comparison 
    $tomorrowInZurich = now('Europe/Zurich')->addDay(1); 
    
    echo "The date/time tomorrow in Zurich will be: {$tomorrowInZurich} \n";
    
    if($tomorrowInZurich->gt($casablanca)) {
        echo "The time {$tomorrowInZurich} is greater than {$casablanca}"; 
    }
    

    You can see a working example here.

    In your particular case, to compare the timestamps, you'd just do:

    $scheduleTime = Carbon::createFromTimestamp($scheduleTime['scheduled_on'] / 1000, 'Africa/Casablanca');
    
    if(now()->gte($scheduleTime)) {
        //
    }
    
    // gte() is just a shorthand for greaterThanOrEqualTo()