基于时区的碳上数秒之间的差值

sum*_*mit 5 php datetime laravel php-carbon

我想找出不同时区2次之间的差异。我的服务器基于悉尼,我想找到给定时间与当前时间(基于珀斯)之间的时差(以秒为单位)

    echo $tz = Carbon::now('Australia/Perth');
    echo "<br>";
    $local='2017-04-11 12:39:50';
    echo $emitted = Carbon::parse($local);
    echo "<br>";
    echo "diff from carbon->";
    echo $diff = $tz->diffInSeconds($emitted); 
    echo "<br> diff from Normal->";
    echo  $diff1 = strtotime($tz) - strtotime($emitted);
Run Code Online (Sandbox Code Playgroud)

当我使用diffInSeconds它时,相差2小时,看起来本地化没有考虑,但strtotime($tz) - strtotime($emitted)给出了理想的结果。我错过了什么吗?

sho*_*ild 8

您必须告诉Carbon哪个时区用于应解析的字符串。我认为strtotime函数不是您的正确选择,因为它始终认为解析的字符串正在使用default_timezone_get()中的时区

例如:

    echo $now = Carbon::now('Australia/Perth');
    echo "<br>";
    echo $emitted = Carbon::parse($now, 'Australia/Sydney');
    echo "<br>";
    echo "diff from carbon->";
    echo $diff = $now->diffInSeconds($emitted);
    echo "<br> diff from Normal->";
    echo  $diff1 = strtotime($now) - strtotime($emitted);
Run Code Online (Sandbox Code Playgroud)

将导致:

diff from carbon->7200
diff from Normal->0
Run Code Online (Sandbox Code Playgroud)

正常的差异显然是错误的,因为$ emited应该使用'Australia / Sydney',而$ now应该使用'Australia / Perth'。但是,由于两个变量具有完全相同的字符串表示形式,因此diff为0。(有关不同时区的信息会丢失)。

但是,与Carbon的差异显示正确的时差为7200秒(= 2小时),这是澳大利亚/悉尼与澳大利亚/珀斯之间的真实差异

默认情况下,所有日期和日期时间函数(包括Carbon)都使用config / app.php文件中timezone变量的值。