laravel carbon 从时间戳中比较两个时区时间

laravel carbon Compare two timezone times from timestamp

我想比较不同时区的时间。时间戳使用 Mutators.My 代码存储在数据库中,如下所示,

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

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

如何将当前时间与 Africa/Casablanca 时区的当前时间进行比较。

我现在做的是

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

我说的对吗?不满足条件

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

请给我建议..任何帮助将不胜感激。

您不需要将其解析为日期时间字符串。如果将它保留为 Carbon 实例,比较起来会容易得多。以下是一些示例:

// 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}"; 
}

您可以看到一个工作示例 here

在您的特定情况下,要比较时间戳,您只需执行以下操作:

$scheduleTime = Carbon::createFromTimestamp($scheduleTime['scheduled_on'] / 1000, 'Africa/Casablanca');

if(now()->gte($scheduleTime)) {
    //
}

// gte() is just a shorthand for greaterThanOrEqualTo()