Open In App

Moment.js moment.duration().weeks() Method

Improve
Improve
Like Article
Like
Save
Share
Report

The moment().duration().weeks() method is used to get the weeks of the duration. This number of weeks is calculated as a subset of the days, therefore having a value between 0 and 4. The length of days for calculating each week is 7 days.

This method is different from the asWeeks() method which returns the length of the given duration in weeks.

Syntax:

moment().duration().weeks();

Parameters: This method does not accept any parameters.

Return Value: This method returns the weeks (0-4) of the duration.

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.duration().weeks() Method.

Example 1: 

Javascript




const moment = require('moment');
  
let durationOne = moment.duration(3, 'weeks');
let durationTwo = moment.duration(6, 'weeks');
  
// This returns 3 as it would be the 3rd week
// in the first month of the duration
console.log(
  "durationOne Weeks is:", durationOne.weeks()
)
  
// This returns 1 as it would be the 1st week
// in the second month of the duration
console.log(
  "durationTwo Weeks is:", durationTwo.weeks()
)


Output:

durationOne Weeks is: 3
durationTwo Weeks is: 1

Example 2: This example will help to understand the difference of this method with asWeeks() for a better understanding.

Javascript




const moment = require('moment');
  
let durationA = moment.duration(30, 'days');
let durationB = moment.duration(38, 'days');
  
// The asWeeks() method will return a value
// of the actual number of weeks of the duration
console.log(
  "Length of durationA in weeks is:",
  durationA.asWeeks()
)
  
// The weeks() method will return 
// the week of the duration
// It can be denoted as floor(numberOfWeeks % 4)
console.log(
  "durationA Weeks is:", durationA.weeks()
)
  
console.log(
  "Length of durationB in weeks is:",
  durationB.asWeeks()
)
console.log(
  "durationB Weeks is:", durationB.weeks()
)


Output:

Length of durationA in weeks is: 4.285714285714286
durationA Weeks is: 4
Length of durationB in weeks is: 5.428571428571429
durationB Weeks is: 1

Reference: https://momentjs.com/docs/#/durations/weeks/



Last Updated : 15 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads