Open In App

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

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:



Calculations: 

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:




// 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:




// 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/


Article Tags :