简体   繁体   中英

laravel blade datetime dynamic timezone on view

I have a view on blade view with DateTime as a column of datatable. the DateTime timezone is UTC. I wanted to change it to the local timezone with the client browser.

so if the data is 00:00 am, then for someone accessing from UTC+5, the DateTime will be 05:00.

the column is currently like this, it generates me 2022-01-02 00:00am :

      <td>
        {{ $data->createdDate->format('d M Y H:ia') }}
      </td>

and then I try to manipulate the DateTime using the timezone below and it works. but I hard-coded the timezone on it. so I got 2022-01-01 19:00pm which is correct (UTC-5).

 {{ $data->createdDate->setTimezone('America/New_York')->format('d M Y H:ia') }}

is there a way to dynamically set the timezone ('America/New_York') on the view page?

because the users could be accessed from different regions.

I know on javascript I can generate the timezone using

Intl.DateTimeFormat().resolvedOptions().timeZone

but how can I pass the timezone to that?

You can pass a timestamp to the blade view and then create local time using javascript, something like this:

PHP

$dt = new DateTime('2020-12-24 4:45',new dateTimeZone('UTC'));  //example
echo '<div id="datejs" data-ts="'.($dt->getTimeStamp() * 1000;).'">?</div>';

Javascript

var el = document.getElementById("datejs");
var ts = parseInt(el.getAttribute("data-ts"));
el.innerHTML = new Date(ts).toLocaleString();

I tested it without Laravel and Blade. Output for my time zone: 24.12.2020, 05:45:00

If a specific formatting of PHP pages is desired, a format string can also be passed via a data element. A framework such as moment.js is then helpful for the formatting itself.

You can add timezone field to users table, then update it once the user login using for example momentjs library on login form. Finally you can easily display the time according to user timezone, something like this:

{{ $data->createdDate->setTimezone(auth()->user()->timezone)->format('d M Y H:ia') }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM