Open In App

Moment.js Customize First Day of Week and First Week of Year

Improve
Improve
Like Article
Like
Save
Share
Report

Moment.js is a JavaScript date library for parsing, validating, manipulating, and formatting dates. In the calendar, we can use Moment.js to customize the First Day of the Week and the First Week of the Year as per our requirements. We will be using the moment.updateLocale() method for this customization.

Syntax:

moment.updateLocale('en', {
    week : {
        dow : Int,
        doy : Int
     }
});

Parameters: This method accepts the locale that has to be updated and the time parameter to be updated. We will be using the week object to update the dow (denoting the day of the week) and doy (denoting the week of the year) values. Both the parameters should be of Integer data type.

Each Integer corresponds to the following days:

  • “0” stands for Sunday.
  • “1” stands for Monday.
  • “2” stands for Tuesday.
  • “3” stands for Wednesday.
  • “4” stands for Thursday.
  • “5” stands for Friday.
  • “6” stands for Saturday.

Calculations: 

  • The doy value is used together with dow to determine the first week of the year.
  • The doy value is calculated as 7 + dow – janX, where janX is the first day of January that must belong to the first week of the year.

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:

Javascript




// Acquiring the plugin
const moment = require("moment");
 
let customized = moment.updateLocale("en", {
    week: {
 
        // Set the First day of week to Sunday
        dow: 0,
 
        // Set the First week of year to
        // contain 3rd January
        doy: 3,
    },
});
 
console.log("Value of dow is:", customized._week.dow);
console.log("Value of doy is:", customized._week.doy);


Output:

Value of dow is: 0
Value of doy is: 3

Example 2:

Javascript




// Acquiring the plugin
const moment = require("moment");
 
let customized = moment.updateLocale("en", {
    week: {
 
        // Set the First day of week to Monday
        dow: 1,
 
        // Set the First week of year to
        // contain 1st January
        doy: 6,
    },
});
 
console.log("Value of dow is:", customized._week.dow);
console.log("Value of doy is:", customized._week.doy);


Output:

Value of dow is: 1
Value of doy is: 6

References: https://momentjs.com/docs/#/customization/dow-doy/



Last Updated : 28 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads