How to Get the Current Date and Time in UTC using JavaScript

To get the current date and time in UTC, use the “Date object’s getUTC*()” method in JavaScript.

Visual representation of getUTC*() methods

Diagram of getUTC*() methods

Example

const now = new Date();

const year = now.getUTCFullYear();
const month = now.getUTCMonth() + 1;
const day = now.getUTCDate();
const hours = now.getUTCHours();
const minutes = now.getUTCMinutes();
const seconds = now.getUTCSeconds();
const milliseconds = now.getUTCMilliseconds();

console.log(`${year}-${month}-${day} 
            ${hours}:${minutes}:${seconds}.${milliseconds}`);

Output

2023-4-15 16:0:42.550

This code example creates a new Date object with the current date and time.

The various getUTC*() methods are called on the Date object to get the year, month, day, hours, minutes, seconds, and milliseconds in UTC.

The getUTCMonth() method returns a zero-based value, so you must add 1 to get the correct month. Finally, the date and time are formatted as a string and logged to the console.

Alternatively, you can use the “toISOString()” method of the Date object to get the current date and time in ISO format.

const now = new Date();

const isoString = now.toISOString();

console.log(isoString);

Output

2023-04-15T16:02:56.036Z

Why should you use the getUTC() method?

The significant advantage of using the getUTC() method is that you can retrieve date and time values that are consistent globally, regardless of the local time zone. It eliminates the inconsistencies.

Some time zones observe DST, which can create complexities when performing date and time calculations.

UTC does not observe DST, making it a stable reference point. UTC is the world’s time standard. Using it ensures that you are referencing a globally recognized and standardized time.

Using getUTC*() methods on the front end ensures that the date and time you work with align with backend systems.

Based on my personal experience, I used to work in a Javascript application where it started growing internationally. Fortunately, I used the getUTC() method, so when I migrated my server to a different time zone, UTC ensured that my date and time handling remained consistent.