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:
<!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> |
Output:
Fri, 12 Apr 2019 05:14:31 GMT
Example-2:
<!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> |
Output:
Fri, 12 Apr 2019 05:39:32 GMT
References
Javascript Date Object
Recommended Posts:
- How to convert milliseconds to date in JavaScript ?
- Convert string into date using JavaScript
- Convert timestamp to readable date/time in PHP
- JavaScript | Date
- JavaScript | Date.now()
- Date.UTC( ) In JavaScript
- JavaScript | Get Date Methods
- JavaScript | date.toLocaleTimeString()
- JavaScript | date.setUTCMonth()
- JavaScript | Date Formats
- JavaScript | Date.parse()
- JavaScript | date.toLocaleDateString()
- JavaScript | date.toLocaleString()
- JavaScript | Set Date Methods
- JavaScript | Date Objects
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.



