JavaScript Date toUTCString() Method

JavaScript Date toUTCString() method is used to convert the given date object’s contents into a string according to the universal time zone UTC.

 The date object is created using the date() constructor. Keep in mind that UTC time is the same as GMT time.

Syntax

dateObj.toUTCString()

Parameters

This method does not accept any parameter.

Return value

It returns the converted string according to the universal time zone UTC.

Example 1: Basic Usage of Date toUTCString()

let date = new Date();

console.log(date.toUTCString());

Output

Wed, 16 Aug 2023 06:34:42 GMT

Example 2: Specific Date

let date = new Date('December 31, 2020 23:59:59');

console.log(date.toUTCString());

Output

Thu, 31 Dec 2020 18:29:59 GMT

Example 3: Date Modification and UTC Conversion

let date = new Date();

date.setHours(date.getHours() + 5);

console.log(date.toUTCString());

Output

Wed, 16 Aug 2023 11:36:53 GMT

Example 4: Write a function that takes a list of values and tries to produce a UTC string

function dateFromValues(values) {
  if (!values || values.length === 0) {
    return new Date().toUTCString();
  }

  try {
    const date = new Date(...values);
    return date.toUTCString();
  } catch (error) {
    return "Invalid values for date construction";
  }
}

const values1 = [2023, 7, 16];
console.log(dateFromValues(values1));

const values2 = [2023, 1, 29, 12, 30];
console.log(dateFromValues(values2));

Output

Tue, 15 Aug 2023 18:30:00 GMT
Wed, 01 Mar 2023 07:00:00 GMT

That’s it!

Related posts

JavaScript Date toUTCString()

JavaScript Date toLocaleDateString()

JavaScript Date toISOString()