Open In App

Moment.js moment().zone() Method

Last Updated : 24 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The moment().zone() method is used to specify the given Moment object’s time zone offset in minutes. An optional parameter can be passed that preserves the current time value and only changes the timezone offset.

Syntax:

moment().zone( Number | String );

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

  • Number | String: It is a number or string that specifies the offset in minutes or hours.

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.

Installation of moment module: Moment.js can be installed using the following command:

npm install moment

Example 1: The below examples will demonstrate the Moment.js moment().zone() Method.

Javascript




const moment = require('moment');
let momentOne = moment();
// Set zone to +120 in minutes
momentOne.zone(120);
console.log(
    "Timezone Offset of MomentOne:", momentOne.zone()
)
console.log("MomentOne is:", momentOne)
let momentTwo = moment();
// Set zone to +240 in minutes
momentTwo.zone(240);
console.log(
    "Timezone Offset of momentTwo:", momentTwo.zone()
)
console.log("MomentTwo is:", momentTwo)
let momentThree = moment();
// Set zone to -350 in minutes
momentThree.zone(-350);
console.log(
    "Timezone Offset of momentThree:", momentThree.zone()
)
console.log("MomentThree is:", momentThree)


Output:

Timezone Offset of MomentOne: 120
MomentOne is: Moment<2022-08-05T12:02:41-02:00>
Timezone Offset of momentTwo: 240
MomentTwo is: Moment<2022-08-05T10:02:41-04:00>
Timezone Offset of momentThree: -350
MomentThree is: Moment<2022-08-05T19:52:41+05:50>

Example 2: The below examples will demonstrate the Moment.js moment().zone() Method.

Javascript




const moment = require('moment');
let moment1 = moment();
// Set zone to +9 in hours
moment1.zone(9);
console.log(
    "Timezone Offset of moment1:", moment1.zone()
)
console.log("moment1 is:", moment1)
let moment2 = moment();
// Set zone to +3 in hours
moment2.zone(3);
console.log(
    "Timezone Offset of moment2:", moment2.zone()
)
console.log("moment2 is:", moment2)
let moment3 = moment();
// Set zone to -8 in hours
moment3.zone(-8);
console.log(
    "Timezone Offset of moment3:", moment3.zone()
)
console.log("moment3 is:", moment3)


Output:

Timezone Offset of moment1: 540
moment1 is: Moment<2022-08-05T05:02:41-09:00>
Timezone Offset of moment2: 180
moment2 is: Moment<2022-08-05T11:02:41-03:00>
Timezone Offset of moment3: -480
moment3 is: Moment<2022-08-05T22:02:41+08:00>

Reference: https://momentjs.com/docs/#/manipulating/timezone-offset/



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads