Open In App

Moment.js Parsing UTC

Last Updated : 10 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Moment.js is a JavaScript date library for parsing, validating, manipulating, and formatting dates. UTC stands for Universal Time Coordinated which is maintained by the Bureau International des Poids et Measures (BIPM).

Moment.js uses the moment() function by default to parse and display in local time. Thus, we need to use moment.utc() function which will implement in UTC mode for all its display methods instead of local time.

Syntax:

moment.utc();
moment.utc(Number);
moment.utc(String);

Parameters: This function will accept a single parameter that denotes the date. It can in the format of a number, string, or date.

Return Value: It returns the date and time in UTC.

Note: This will not work in the normal Node.js program because it requires the moment.js library to be installed.

Moment.js can be installed using the following command:

npm install moment

Example 1: Implementing moment.utc() function

Javascript




// Acquiring the pluggin
const moment = require("moment");
 
// Local time
let a = moment();
 
// UTC time
let b = moment.utc();
 
console.log("Using Local time:", a);
console.log("Using UTC Mode:", b);


Output:

Using Local time: Moment<2022-12-13T22:33:50+05:30>
Using UTC Mode: Moment<2022-12-13T17:03:50Z>

Example 2: Passing parameters to moment.utc() function

Javascript




// Acquiring the pluggin
const moment = require("moment");
 
let a = moment();
let b = moment.utc(1);
let c = moment.utc("2005-06-10");
 
console.log("Using Local time:", a);
console.log("Using UTC Mode:", b);
console.log("Using UTC Mode:", c);


Output:

Using Local time: Moment<2022-12-13T22:40:09+05:30>
Using UTC Mode: Moment<1970-01-01T00:00:00Z>
Using UTC Mode: Moment<2005-06-10T00:00:00Z>

References: https://momentjs.com/docs/#/parsing/utc/


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads