0

I am unable to get the time for a particular timezone using Laravel 8. I have tried the following:

Carbon::now(new \DateTimeZone('Indian/Mauritius'))

I have also tried to modify the timezone in file config\app.php as follows:

'timezone' => 'Indian/Mauritius'

It is always returning me the UTC time. How to get the time using Carbon in that specific timezone?

Edits: issue solved, the problem was because of a serialization issue, check here

Noor
  • 19,638
  • 38
  • 136
  • 254

1 Answers1

0

This works for me:

$dateNow = \Carbon\Carbon::now();
$dateNow->setTimezone('Indian/Mauritius');
jssDev
  • 923
  • 5
  • 18
  • What do you mean? $dateNow has no value after running? – jssDev Jul 13 '21 at 12:24
  • no, ypur code is returning me `2021-07-13T12:32:11.585651Z` while it's 16:32 in Mauritius – Noor Jul 13 '21 at 12:32
  • I have tested my code, inspecting the $dateNow variable after setTimezone() and the value is correct. I'm pretty sure you mean the data value in the JSON response (which you don't mention) and the problem is in serialization. Take a look at this: https://stackoverflow.com/questions/60649769/wrong-timezone-in-laravel-7-after-date-serialization# – jssDev Jul 13 '21 at 12:42
  • you can check this by simply doing this: $dateNow = \Carbon\Carbon::now()->setTimezone('Indian/Mauritius')->toDateTimeString(); – jssDev Jul 13 '21 at 13:00
  • you are right, never even thought about the serialization issue – Noor Jul 13 '21 at 13:16
  • do you have any idea where the configuration in config/app.php isn't working – Noor Jul 13 '21 at 13:19
  • Yes, it should works. If you have set it up, your default Carbon object datetime should be the local hour in Mauritius (not in serialized data) – jssDev Jul 14 '21 at 07:03