Work Laravel 5.3 + Vue.JS 1.0 - Display Dates in User's Local Time

Laravel 5.3 + Vue.JS 1.0 - Display Dates in User's Local Time

19th Sep, 2016 | Work

PS: Continuation of our Laravel + VueJS series.

The objective here is to ensure the created_at and updated_at times  are displayed relative to the time on the device the user is viewing the application on. This is as opposed to the server time - which by default, we have set to UTC in our server side config:

'timezone' => 'UTC',

You can see the current UTC time here.

To achieve this, it is actually pretty easy with a line of Javascript - but as we are using VueJs and we also want to format the date to look nice, let us pull in momentjs.
Inside package.json:

"moment": "^2.15.0"

And then npm install to install the new dependency.
Inside our resources/assets/js/bootstrap.js:

window.moment = require('moment');

And then finally inside our resources/assets/js/components/MailingLists.vue, after methods {}, we add:

filters: {
    localTime: function (date) {
       return moment(date + ' Z', 'YYYY-MM-DD HH:mm:ss Z', true).format('D MMM YYYY HH:mm');

This localTime takes the mysql date in YYYY-MM-DD HH:mm:ss format and adds a ' Z' to it. This ' Z' effectively tells it to change that the original date is UTC but we want it relative to user's local time. After this, we format it so that it would display as such: 19 Sep 2016 18:53

Finally, we use the filter in our markup:

<tr v-for="mList in mLists | orderBy orderAttr orderToggle">
    <td>{{ }}</td>
    <td>{{ mList.created_at | localTime }}</td>
    <td>{{ mList.updated_at | localTime }}</td>

And result:

To test it, you can change your computer time and see your created_at and updated_at columns adapt.

The Github code for this post is this way.