Open In App

How to get JavaScript Date in UTC using MomentJS?

Last Updated : 30 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

When working with dates and times in JavaScript, especially in applications that deal with users across different time zones, it is often necessary to work with dates in UTC (Coordinated Universal Time).

Below are the approaches to get a date in UTC using Moment.js:

Using moment().utc() to get the current date and time in UTC

This approach is used to get the current date and time in UTC. The moment().utc() method returns a Moment object representing the current date and time in UTC.

Example: In this example we are using the moment().utc() method to get the current date and time in UTC.

JavaScript
const moment = require('moment');

const utcDate = moment().utc();
console.log(utcDate.format());

Output:

2024-08-28T11:09:30Z

Creating a specific date in UTC using moment.utc()

When we need to create a date in UTC we can use the moment.utc() method and pass the specific date and time as arguments. This method is useful when working with historical dates or scheduled events.

Example: In below example we are using creating the specific date in UTC.

JavaScript
const moment = require('moment');

const utcSpecificDate = moment.utc('2024-08-28T12:34:56');
console.log(utcSpecificDate.format());

Output:

2024-08-28T12:34:56Z

Converting an existing Moment object to UTC using moment.local().utc()

When we have a local date and time that we need to convert to UTC we can first create a Moment object in local time and then use the .utc() method to convert it to UTC.

Example: In below example we are converting the the local time to the UTC.

JavaScript
const moment = require('moment');

const localDate = moment('2024-08-28T12:34:56');
const utcDate = localDate.utc();
console.log(utcDate.format());

Output:

2024-08-28T12:34:56Z

Next Article

Similar Reads