The moment().utcOffset() method is used to specify the given Moment object’s UTC offset. An optional parameter can be passed that preserves the current time value and only changes the offset.
Syntax:
moment().utcOffset( Number | String, [Boolean] );
Parameters: This method accepts two parameters as mentioned above and described below:
- Number | String: It is a number or string that specifies the offset in minutes or hours.
- Boolean: It is an optional boolean value that specifies whether the offset would be changed without modifying the actual time itself.
Return Value: This method returns the Moment object with the new offset.
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().utcOffset() Method.
Example 1:
Javascript
const moment = require( 'moment' ); let momentOne = moment(); // Set UtcOffset to +60 in minutes momentOne.utcOffset(60); console.log( "Utc Offset of MomentOne:" , momentOne.utcOffset() ) console.log( "MomentOne is:" , momentOne) let momentTwo = moment(); // Set UtcOffset to +150 in minutes momentTwo.utcOffset(150); console.log( "Utc Offset of momentTwo:" , momentTwo.utcOffset() ) console.log( "MomentTwo is:" , momentTwo) let momentThree = moment(); // Set UtcOffset to -510 in minutes momentThree.utcOffset(-510); console.log( "Utc Offset of momentThree:" , momentThree.utcOffset() ) console.log( "MomentThree is:" , momentThree) |
Output:
Utc Offset of MomentOne: 60 MomentOne is: Moment<2022-08-05T14:56:08+01:00> Utc Offset of momentTwo: 150 MomentTwo is: Moment<2022-08-05T16:26:08+02:30> Utc Offset of momentThree: -510 MomentThree is: Moment<2022-08-05T05:26:08-08:30>
Example 2:
Javascript
const moment = require( 'moment' ); let moment1 = moment(); // Set UtcOffset to +2 in hours moment1.utcOffset(2); console.log( "Utc Offset of moment1:" , moment1.utcOffset() ) console.log( "moment1 is:" , moment1) let moment2 = moment(); // Set UtcOffset to +5 in hours moment2.utcOffset(5); console.log( "Utc Offset of moment2:" , moment2.utcOffset() ) console.log( "moment2 is:" , moment2) let moment3 = moment(); // Set UtcOffset to -6 in hours moment3.utcOffset(-6); console.log( "Utc Offset of moment3:" , moment3.utcOffset() ) console.log( "moment3 is:" , moment3) |
Output:
Utc Offset of moment1: 120 moment1 is: Moment<2022-08-05T15:56:08+02:00> Utc Offset of moment2: 300 moment2 is: Moment<2022-08-05T18:56:08+05:00> Utc Offset of moment3: -360 moment3 is: Moment<2022-08-05T07:56:08-06:00>
Reference: https://momentjs.com/docs/#/manipulating/utc-offset/