laravel 基于时区的碳上两次时间的差异(以秒为单位)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43337104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between two times in seconds on carbon based on timezone
提问by sumit
I want to find out the difference between 2 times for the different timezone. My server is based on Sydney and I want to find the difference between given time and current time(based on Perth) in seconds
我想找出不同时区的 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);
When I used diffInSeconds
it gave 2 hours difference and looks like localisation is not taken consideration
but strtotime($tz) - strtotime($emitted)
gives perfect result. Any thing I missed?
当我使用diffInSeconds
它时,它给出了 2 小时的差异,看起来没有考虑本地化,但strtotime($tz) - strtotime($emitted)
给出了完美的结果。我错过了什么吗?
回答by shock_gone_wild
You have to tell Carbon which timezone is used for the string that should be parsed. The strtotime function is not the right choice for you I think, because it always consideres the parsed strings to be using the timezone from default_timezone_get()
您必须告诉 Carbon 哪个时区用于应该解析的字符串。我认为 strtotime 函数不是您的正确选择,因为它始终认为解析的字符串使用default_timezone_get() 中的时区
For example:
例如:
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);
Would result in :
会导致:
diff from carbon->7200
diff from Normal->0
The normal diff is obviously wrong as $emitted is supposed to use 'Australia/Sydney' and $now is supposed to use 'Australia/Perth'. But as the two variables have the exact same string representation the diff is 0. (The information about the different timezones is lost).
正常的差异显然是错误的,因为 $emitted 应该使用“Australia/Sydney”,而 $now 应该使用“Australia/Perth”。但是由于这两个变量具有完全相同的字符串表示形式,因此差异为 0。(有关不同时区的信息丢失)。
The diff with Carbon however shows the correct difference of 7200 Seconds (= 2 hours ) which is the real difference between Australia/Sydney and Australia/Perth
然而,与 Carbon 的差异显示了 7200 秒(= 2 小时)的正确差异,这是澳大利亚/悉尼和澳大利亚/珀斯之间的真正差异
By default all the date and date-time functions (including Carbon) are using the value from the timezonevariable in your config/app.phpfile.
默认情况下,所有日期和日期时间函数(包括 Carbon)都使用config/app.php文件中时区变量的值。