基于时区的碳在两秒之间的差异

时间:2017-04-11 05:00:35

标签: php laravel datetime 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);

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

1 个答案:

答案 0 :(得分:7)

你必须告诉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);

会导致:

diff from carbon->7200
diff from Normal->0

普通差异显然是错误的,因为$ emit应该使用&#39;澳大利亚/悉尼&#39;而$ now应该使用&#39; Australia / Perth&#39;。但由于两个变量具有完全相同的字符串表示,因此diff为0.(关于不同时区的信息丢失)。

然而,与碳的差异显示7200秒(= 2小时)的正确差异,这是澳大利亚/悉尼和澳大利亚/珀斯之间的真正差异

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