Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get All Monday Dates In Month using Moment,js

Is there any way to get all the Monday DATES in the current month using moment.js library.

I know I can get the end of the month with:

moment().endOf('month')

but how to get all monday dates of current / any month.

I dont want some function in javascript default date library. Please refer the code using Moment Js Library.

like image 201
Shan Khan Avatar asked Nov 09 '15 23:11

Shan Khan


People also ask

How do you get all dates in a month in a moment?

The moment(). daysInMonth() function is used to get the number of days in month of a particular month in Node. js.

What is replacing moment JS?

There are several libraries out there that can potentially replace Moment in your app. The creators of Moment recommend looking into Luxon, Day. js, date-fns, js-Joda, or even replacing Moment with native JS.

What is Moment () in JavaScript?

Moment JS allows displaying of date as per localization and in human readable format. You can use MomentJS inside a browser using the script method. It is also available with Node. js and can be installed using npm.


2 Answers

I've just read docs and haven't found any method that returns an array, so you need to do it only with loop

var monday = moment()
    .startOf('month')
    .day("Monday");
if (monday.date() > 7) monday.add(7,'d');
var month = monday.month();
while(month === monday.month()){
    document.body.innerHTML += "<p>"+monday.toString()+"</p>";
    monday.add(7,'d');
}

check this out

like image 137
Danil Gudz Avatar answered Sep 17 '22 10:09

Danil Gudz


Update

I made a little drop in for this. Add it to your page:

<script src="https://gist.github.com/penne12/ae44799b7e94ce08753a/raw/moment-daysoftheweek-plus.js"></script>

And then:

moment().allDays(1) //=> [...]
moment().firstDay(1)

etc - feel free to check out the source

Old Post

This function should work:

function getMondays(date) {
    var d = date || new Date(),
        month = d.getMonth(),
        mondays = [];

    d.setDate(1);

    // Get the first Monday in the month
    while (d.getDay() !== 1) {
        d.setDate(d.getDate() + 1);
    }

    // Get all the other Mondays in the month
    while (d.getMonth() === month) {
        mondays.push(new Date(d.getTime()));
        d.setDate(d.getDate() + 7);
    }

    return mondays;
}

Usage: getMondays() for this month, or getMondays(moment().month("Feb").toDate()) for a different month.

From jabclab's Stack Overflow Answer, modified to include custom date param.

like image 40
Ben Aubin Avatar answered Sep 19 '22 10:09

Ben Aubin