JavaScript toUTCString(): Get the complete date as a string according to UTC

The JavaScript toUTCString() method is used to get the complete date as a string based on the Universal Time Coordinated (UTC) or Greenwich Mean Time (GMT). For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <p id="xyz"></p>

   <script>
      const d = new Date();
      let dateUTC = d.toUTCString();
      document.getElementById("xyz").innerHTML = dateUTC;
   </script>

</body>
</html>
Output

In the above example, the following JavaScript statement:

const d = new Date();

creates a new "Date" object with the "new Date()" constructor. This method generates a new date and time object using the current system clock time.

Then the following JavaScript statement:

let dateUTC = d.toUTCString();

calls the Date object's toUTCString() method to convert the date and time to a string representation in UTC format. This string represents the date and time in a standard time zone-independent format. The string that results is saved in the dateUTC variable.

Finally, the following JavaScript statement:

document.getElementById("xyz").innerHTML = dateUTC;

finds the HTML element with the id attribute "xyz" and sets its innerHTML property to the value stored in the dateUTC variable using the document.getElementById() method. The current date and time in UTC format will be displayed on the web page.

JavaScript toUTCString() syntax

The syntax of the toUTCString() method in JavaScript is:

x.toUTCString()

where x must be an object of the Date() constructor.

The toUTCString() method returns a string representing the UTC date and time.

Please note: To display the date in format dd-mm-yyyy, refer to its separate example.

Please note: To display time in the format hh:mm:ss, refer to its separate example.

Please note: To display time in the format hh:mm:ss AM/PM, refer to its separate example.

Advantages of the toUTCString() method in JavaScript

Disadvantages of the toUTCString() method in JavaScript

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!