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

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

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

In this code example, a new Date object is created 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 time.

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

In this code example, the toISOString() method is called on the Date object to get the current date and time in ISO format.

Leave a Comment