How to get your local time from UTC/GMT time using Moment.JS with example

By | April 4, 2019
How to get your local time from UTC/GMT time using Moment.JS with example

Hello friends, in this article i will let you know how to get your local time from UTC/GMT time using Moment.JS. While working on any project as a developer we generally need to work with date manipulation.

There are too many procedures  available to manipulate date. But here we will work with moment.js.

In this example we will take utc time by using moment js and will convert it into local system’s time.

<!DOCTYPE html>
<html>
<head>
  <title>How to get your local time from UTC/GMT time using Moment.JS </title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"><script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.min.js"></script> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <center>
                <h4>How to get your local time from UTC/GMT time using Moment.JS</h4>
                <hr>
            </center>
        </div>
        <div class="col-md-8 col-md-offset-2">
            <div class="col-md-6">
                <p><strong>Currant UTC Time</strong></p>
                <div id="utc-time"></div>
            </div>

            <div class="col-md-6">
                <p><strong>Your Local Time with respect to UTC time</strong></p>
                <div id="local-time"></div> 
            </div> 
        </div>
    </div>
</div>


<script type="text/javascript">
 // Function to update utc and local time every second
 $(function(){
      setInterval(function(){
        var utcTime = $('#utc-time');
        var localTime = $('#local-time');  
        // Putting current utc time in a div having id utc-time
        utcTime.text(moment.utc().format('YYYY-MM-DD HH:mm:ss'));  

        // Getting user's local time converted from above utc time    
        var formattedTime  = moment.utc(utcTime.text()).toDate();
        formattedTime = moment(formattedTime).format('YYYY-MM-DD HH:mm:ss');
        localTime.text(formattedTime);        
      },1000);
 });
</script>
</html>