Manipulating Dates with Day.js — Set the Week of the Year and Month of a Date | by John Au-Yeung | Apr, 2024
Day.js is a JavaScript library that lets us manipulate dates in our apps.
In this article, we’ll look at how to use Day.js to manipulate dates in our JavaScript apps.
To set the week of the year in a Day.js date we can use the weekOfYear
method available with the weekOfYear
plugin:
const dayjs = require("dayjs");
const weekOfYear = require("dayjs/plugin/weekOfYear");
dayjs.extend(weekOfYear);const result = dayjs().week(1);
console.log(result);
We import the weekOfYear
plugin with:
const weekOfYear = require("dayjs/plugin/weekOfYear");
And we set the week of the year to the first week by calling week
with 1.
To set the ISO week of the year in a Day.js date we can use the isoWeek
method available with the isoWeek
plugin:
const dayjs = require("dayjs");
const isoWeek = require("dayjs/plugin/isoWeek");
dayjs.extend(isoWeek);const result = dayjs().isoWeek(1);
console.log(result);
We import the isoWeek
plugin with:
const isoWeek = require("dayjs/plugin/isoWeek");
And we set the ISO week of the year to the first week by calling isoWeek
with 1.
To set the month of Day.js date we can use the month
method:
const dayjs = require("dayjs");
const result = dayjs().month(1);
console.log(result);
We call month
with 1 to set the month the date to February. Month ranges from 0 for January to 11 for December.
Day.js is a JavaScript library that lets us manipulate dates in our apps.