How to get Local Time Instead of Server Time

  423 views   8 months ago Javascript

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="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.27/moment-timezone-with-data-2012-2022.min.js"></script>

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

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

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
        $('#post-time').html(time);
    });
</script>

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.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]