我想比较不同时区的时间。时间戳使用Mutators存储在数据库中。我的代码如下所示,
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
}
请建议我。任何帮助,我们将不胜感激。
答案 0 :(得分:1)
您无需将其解析为日期时间字符串。如果将其保留为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()