How to convert a JavaScript date to UTC?

The Javascript date can be converted to UTC by using functions present in Javascript Date object.
The toUTCString() method is used to convert a Date object into a string, according to universal time.
The toGMTString() returns a string which represents the Date based on the GMT (UT) time zone.

By default, JavaScript uses the browser’s time zone and display a date as a full-text string:
Fri Apr 12 2019 10:32:15 GMT+0530 (India Standard Time).

To create a new Date object we use javascript Date() constructor.


Syntax:



dateObj.toUTCString()

Example-1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, 
                   initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" 
          content="ie=edge">
    <title>
      Document
  </title>
</head>
  
<body>
    <div id="date">
  
    </div>
</body>
<script>
    var d = new Date();
    var n = d.toUTCString();
    var e = document.querySelector("#date");
    e.innerHTML = n;
</script>
  
</html>

chevron_right


Output:

Fri, 12 Apr 2019 05:14:31 GMT

Example-2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width,
                   initial-scale=1.0">
    
    <meta http-equiv="X-UA-Compatible" 
          content="ie=edge">
    <title>
      Document
  </title>
</head>
  
<body>
    <div id="date">
  
    </div>
</body>
<script>
    var d = new Date();
    var e = document.querySelector("#date");
    e.innerHTML = d.toGMTString();
</script>
  
</html>

chevron_right


Output:

Fri, 12 Apr 2019 05:39:32 GMT

References
Javascript Date Object



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.