skip to Main Content

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 a.m., 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?

2

Answers


  1. 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') }}
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search