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
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?
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()
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).
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
By default all the date and date-time functions (including Carbon) are using the value from the timezone variable in your config/app.php file.