JavaScript date.toUTCString() method


The date.toUTCString() method in JavaScript converts a Date object to a string representing the date and time in Coordinated Universal Time (UTC). This method provides a standardized format that is useful for applications that need to work with UTC time.

Syntax:

date.toUTCString();

Returns:

  • A string representing the date and time in UTC format, typically formatted as: Day, DD Mon YYYY HH:mm:ss GMT.

Example 1: Default UTC Representation

const date = new Date('2024-10-22T14:30:00Z'); // Z indicates UTC console.log(date.toUTCString());

Output:

Tue, 22 Oct 2024 14:30:00 GMT

Explanation:

  • The output includes:
    • Day: Tue (Tuesday)
    • Date: 22
    • Month: Oct (October)
    • Year: 2024
    • Time: 14:30:00 (in 24-hour format)
    • Time Zone: GMT

Example 2: Current UTC Time

const now = new Date(); console.log(now.toUTCString());

Output (Example):

Tue, 22 Oct 2024 14:30:00 GMT

Explanation:

  • The output will vary based on the current date and time when the code is executed, but it will follow the same UTC format.

Example 3: UTC from Different Dates

const date1 = new Date(); // Current date and time const date2 = new Date(2024, 9, 22, 9, 15, 30); // October 22, 2024, 09:15:30 AM console.log(date1.toUTCString()); console.log(date2.toUTCString());

Output (Example):

Tue, 22 Oct 2024 14:30:00 GMT Tue, 22 Oct 2024 09:15:30 GMT

Explanation:

  • The first output shows the current date and time in UTC.
  • The second output shows the UTC representation for the specific date created (October 22, 2024, at 09:15:30 AM).

Summary:

  • The date.toUTCString() method is useful for obtaining a string representation of the date and time in a standard UTC format.
  • This method is especially helpful in applications that require consistent time representation across different time zones, as it eliminates ambiguity related to local time.