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?
Use floor($totalDuration / 3600) . gmdate(":i:s", $totalDuration % 3600) to get durations > 24 hours, e.g. 72:16:12 (72 hours, 16 minutes, 12 seconds).
First, you set the timezone you initially have, so if you store your date in the database as UTC, then set the default timezone to UTC, then use ->setTimeZone('Valid/Timezone') to make the change from what you'v had to the new timezone. Save this answer.
If you need to add hour or more hours in date then you can use carbon in laravel. carbon provide addHour() and addHours() method to add hours on carbon date object.
Whenever you need to get difference between two dates in hours in laravel then you can get easily using Carbon. Laravel by default provide Carbon class. Carbon class throught you can calculate difference between two dates in hours. you can use this example with laravel 6, laravel 7, laravel 8 and laravel 9 version.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With