Get the count of passed days from start of month till today using moment.js

Viewed 282

Does any body know, any method provided by moment.js to get the days count that are passed till today (include current day too) for the current month.

Let say current days is: 05-03-2020 (dd-mm-yyyy)

let count_of_days = moment().getPassedDays()

console.log(count_of_days) // output 5

Some Solutions I tried:

1-

let count_of_days = moment().days() + 1
console.log(count_of_days) // 5

2-

let count_of_days = parseInt(moment().format("DD")) + 1
console.log(count_of_days) // 5

3-

let start_of_month = moment().startOf("month")

let curr_day_of_month = moment()

let count_of_days = start_of_month.diff(curr_day_of_month, "days") + 1
console.log(count_of_days) // 5
2 Answers

I think date() function return what you're looking for

console.log(moment().date()) //  Return 5

Going by the documentation, there is no such inbuilt function. However, Moment provides a very useful method called diff() that will do your job.

First, get the start date of the month.

var startDate = moment().startOf('month');

Secondly, pass your input date till you want the days i.e. in your case its the current day.

var endDate = moment(new Date());

Use diff method()

var difference = endDate.diff(startDate, 'days');

Since you want the current day as well, add 1 to it and voila! There's your result!

var output = difference + 1;
Related