JavaScript date.getUTCSeconds() method


The date.getUTCSeconds() method in JavaScript returns the seconds (from 0 to 59) of a specified Date object according to Universal Coordinated Time (UTC). This method is useful for obtaining the seconds of a date without considering local time zone differences.

Syntax:

date.getUTCSeconds();

Returns:

  • An integer representing the seconds of the minute (from 0 to 59).

Example 1: Getting UTC Seconds for a Specific Date

const date = new Date('2024-10-22T15:30:45Z'); // October 22, 2024, at 15:30:45 UTC const utcSeconds = date.getUTCSeconds(); console.log(utcSeconds);

Output:

45

Explanation:

  • The Date object represents October 22, 2024, at 15:30:45 UTC. The getUTCSeconds() method returns 45, which corresponds to the seconds in the given time.

Example 2: Getting UTC Seconds for a Local Time

const localDate = new Date('2024-10-22T12:00:30'); // October 22, 2024, at 12:00:30 PM local time const utcSecondsFromLocal = localDate.getUTCSeconds(); console.log(utcSecondsFromLocal);

Output:

30

Explanation:

  • If the local time is 12:00:30 PM, this will convert to a different UTC time depending on the local timezone. If your local timezone is UTC-3, then it would convert to 3:00:30 PM UTC. The getUTCSeconds() method returns 30, which corresponds to the seconds in that UTC time.

Example 3: Getting UTC Seconds for a Date Near Midnight

const nearMidnightLocal = new Date('2024-10-31T23:59:59'); // October 31, 2024, at 11:59:59 PM local time const utcSecondsNearMidnight = nearMidnightLocal.getUTCSeconds(); console.log(utcSecondsNearMidnight);

Output:

59

Explanation:

  • If your local timezone is UTC-3, then the local time of 23:59:59 on October 31 will convert to 02:59:59 UTC on November 1. Therefore, getUTCSeconds() returns 59, representing the last second before midnight in UTC.

Example 4: Getting UTC Seconds for a Date Object Created with UTC

const utcDate = new Date(Date.UTC(2024, 9, 22, 15, 30, 10)); // October 22, 2024, at 15:30:10 UTC const utcSecondsCreated = utcDate.getUTCSeconds(); console.log(utcSecondsCreated);

Output:

10

Explanation:

  • The Date.UTC() method creates a date object for October 22, 2024, at 15:30:10 in UTC. The getUTCSeconds() method returns 10, confirming the correct seconds in the UTC time.

Summary:

  • date.getUTCSeconds() returns the seconds of a Date object in UTC, ranging from 0 to 59.
  • This method is helpful for working with time in a consistent manner, independent of local timezone adjustments.