Open In App

Moment.js moment().toISOString() Method

Improve
Improve
Like Article
Like
Save
Share
Report

The `moment().toISOString()` method is employed to obtain a string formatted according to the ISO8601 standard for a given moment. It ensures consistency with the JavaScript native Date API by using the UTC mode for the timestamp, regardless of the moment’s locale. If you want to disable this behavior, you can pass `true` to the `keepOffset` parameter.

Note: The library will try to use the native Date toISOString() method for better performance.

Syntax:

moment().toISOString( keepOffset );

Parameters: This method accepts a single parameter as mentioned above and described below:

  • keepOffset: This parameter is used to specify whether UTC conversion is enabled or not. It is an optional parameter.

Return Value: This method returns the Moment in the ISO8601 format.

Note: This will not work in the normal Node.js program because it requires an external moment.js library to be installed globally or in the project directory.

Moment.js can be installed using the following command:

Installation of moment module:

npm install moment

The below examples will demonstrate the Moment.js moment().toISOString() Method.

Example 1: Below is the code for the moment().toISOString():

Javascript




const moment = require('moment');
 
let momentOne = moment();
console.log(
    "MomentOne toISOString():", momentOne.toISOString()
)
 
let momentTwo = moment("01-10-2022", "MM-DD-YYYY");
console.log(
    "MomentTwo toISOString():", momentTwo.toISOString()
)
 
let momentThree = moment("05:15:44", "hh:mm:ss");
console.log(
    "MomentThree toISOString():", momentThree.toISOString()
)


Output:

MomentOne toISOString(): 2022-06-28T17:22:45.536Z
MomentTwo toISOString(): 2022-01-09T18:30:00.000Z
MomentThree toISOString(): 2022-06-27T23:45:44.000Z

Example 2: Below is the code for the moment().toISOString():

Javascript




const moment = require('moment');
 
let moment1 = moment().year(2010);
console.log(
    "Moment1 toISOString():", moment1.toISOString()
)
 
let moment2 = moment1.add(10, 'days');
console.log(
    "Moment2 toISOString():", moment2.toISOString()
)
 
let moment3 = moment2.add(20, 'hours');
console.log(
    "Moment3 toISOString():", moment3.toISOString()
)


Output:

Moment1 toISOString(): 2010-06-28T17:22:45.552Z
Moment2 toISOString(): 2010-07-08T17:22:45.552Z
Moment3 toISOString(): 2010-07-09T13:22:45.552Z


Last Updated : 25 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads