Convert UTC date time to local date time using jQuery

Learn, how can we convert the UTC date time to your local date time using jQuery?
Submitted by Pratishtha Saxena, on March 03, 2023

Converting UTC date time to local date time

Firstly, let’s understand what is UTC date time. UTC, aka Coordinated Universal Time, is a world date time standard for regulating the clocks. It is effectively a successor to GMT (Greenwich Mean Time). Hence, when working amongst different time zones, the UTC date time format is chosen for removing confusion. Now, over here we need to see how to convert this UTC to our local time zone using jQuery?

jQuery toLocalString() Method

In jQuery, we have a method known as toLocalString(). This method is used along with the date and time, which further returns a date time string converted to the local time zone.

Syntax

givenDate.toLocaleString();

Similarly, we can also convert a local time to a UTC date time format. For this, the method used is toUTCString(). By using these simple methods, the date formats can be changed as required and needed accordingly. People generally prefer their local time format for working, but always keep in mind to follow a proper time format when interacting between different time zones in the world.

The example given below shows the implementation of these methods for a given date and time. By clicking the provided button, the given UTC will be converted to your local time based on your computer’s time zone settings.

jQuery example to convert UTC date time to local date time

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <title>Document</title>
  </head>
  
  <body>
    <h2>Convert UTC date time to local date time</h2>
    <h4>Click the button to get the local time according to your browser.</h4>
    <button>Get Date & Time</button>
    <hr>
    <p>Welcome to Include Help !!!</p>
    <p>jQuery Tutorial</p>
    <p>Thanks for Visiting !!!</p>
    <h4 id="date"></h4>
    <hr>
    <h4 id="one"></h4>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function () {
        var theDate = new Date('02 March 2023 1:44:48 PM UTC');
        $('h4#date').html('UTC Date Time : ' + theDate.toUTCString());  // UTC Date Time Format
    
        $('button').click(function () {
            $('h4#one').html('Local Date Time : ' + theDate.toLocaleString());  // Local Date Time Format (Indian Standart Time)
        })
    });    
  </script>  
</html>

Output:

Example: Convert UTC date time to local date time using jQuery



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.