Home > Back-end >  Change timezone with Carbon
Change timezone with Carbon

Time:10-07

I have a date that is coming from database (type date):

2018-08-25

This date is in french timezone.

When I do:

    $from = Carbon::parse("2018-08-25", 'Europe/Paris');
    $from->timezone('UTC');
    dd($from);

I get:

  date: 2018-08-24 22:00:00.0 UTC ( 00:00)

Which is what I want

But when I use field from DB:

    $operation = Operation::findOrFail($request->operation);
    $from = Carbon::parse($operation->date_ini, 'Europe/Paris');
    $from->timezone('UTC');
    dd($from);

I get:

date: 2018-08-25 00:00:00.0 UTC ( 00:00)

In my DB, field is saved as : 2018-08-25, so literraly, it means 2018-08-25 UTC. So result is coherent. But I'm not sure how to deal with it to get what I want. The implication would be that I have to store my date like a datetime in DB so that I can store it in UTC with 1 or 2 hours less. Is there anyway to avoid this and keep it simple ?

Any idea ?

CodePudding user response:

I solved it using:

$from = Carbon::parse($operation->date_ini)->shiftTimezone('Europe/Paris');;

shiftTimezone with change timezone without changing the date. So, it do the trick for me !

CodePudding user response:

If you call setTimezone() on an existing instance of Carbon, it will change the date/time to the new timezone, for example

$changeTimeZone =  \Carbon\Carbon::parse($operation->date_ini)->setTimezone('Asia/Dhaka')->format('H:i');
  • Related