JavaScript Date toUTCString() Method



The JavaScript Date.toUTCString() method is used to convert a date object as a string, according to Coordinated Universal Time (UTC). When you create a Date object in JavaScript, it represents a specific point in time, but it doesn't have a time zone associated with it. But this method allows you to convert this date object into a string representation that indicates it's in the UTC timezone.

UTC stands for Coordinated Universal Time. It is the primary time standard by which the world regulates clocks and time.

The JavaScript "Date.toGMTString()" is an alias of this method.

Syntax

Following is the basic syntax of JavaScript Date toUTCString() method −

toUTCString();

This method does not accept any parameters.

Return Value

This method returns a string representing the given date in the UTC timezone.

Example 1

Following is the basic demonstration of the JavaScript Date toUTCString() method −

<html>
<body>
<script>
   const date = new Date();
   const UTCString = date.toUTCString();

   document.write(UTCString);
</script>
</body>
</html>

Output

It returns the Date object as a string, according to UTC.

Example 2

In the following example, we are creating a Date object for a specific date and time, then converting it to a string in the UTC format.

<html>
<body>
<script>
   const specificDate = new Date('2023-01-01T12:00:00');
   const UTCString = specificDate.toUTCString();

   document.write(UTCString);
</script>
</body>
</html>

Output

The above program returns "Sun, 01 Jan 2023 06:30:00 GMT" as result.

Example 3

If the Date object is invalid, this method will return "Invalid date" as a result −

<html>
<body>
<script>
   const specificDate = new Date('2023764-01-01T12:00:00');
   const UTCString = specificDate.toUTCString();

   document.write(UTCString);
</script>
</body>
</html>

Output

As we can see in the output, it didn't returned the Date object in date string format.

Advertisements