How to display user's local time instead of server's time

Suppose you are managing blog website and your user-base location are different instead of specific region. In the blog, you are displaying post creation date and times, so it is become important that you display different time according to user's location time instead of your server's time. In this article we will display time according to user timezone instead of server time. For displaying time, we will use Moment.js library. You can also use 3rd party API services, like GeoIP to get user's timezone from their IP addresses.

Moment.js is the most innovative Javascript library for displaying and manipulating time. It is designed to work in the browser and Node.js.

To use moment.js, first include bellow moment.js CDN file.

<script src=""></script>
<script src=""></script>

And this is the element you want to display time in the blog post.

<div class="post">
    <span id="post-time"></span>

For the simplicity, we have used jQuery to understand code easily. We had used PHP as backend language to get server time and assigned it to Javascript variable.

<script type="text/javascript">
    $(document).ready(function() {

        // created Javascript variable
        var createdAt = moment('<?php echo($post->created_at) ?>');

        // get timezone different between local server to UTC timezone
        var timeDifference = new Date().getTimezoneOffset();

        // change time according to local time from server time
        var time = moment(createdAt).subtract(timeDifference, 'minutes').format('DD/MM/YYYY, hh:mm:ss A');

        // change time in element

That's it. <span id="post-time"> will change server time to user's local time. You can add format() method to change format of the time you want to display. I Hope you like this article. In upcoming article, we will discuss usage of Moment.js.