0
votes

I'm using momentjs to work with dates, I get the current week using:

var startDate =  moment().startOf('isoweek');
var endDate = moment().endOf('isoweek');
var weekDays = getWeekDays(startDate, endDate);

where the function getWeekDays is implemented as the follow:

function getWeeDays(startDate, endDate) {
        "use strict";

        var days = [];
        var day = startDate;

        while (day <= endDate) {
            days.push(day);
            day = day.clone().add(1, 'd');
        }

        return days;
    }

This works pretty well, but now i need to get the days not of the current week but of the week of a target date. For example the user input me the date 24/05/2016 and i need to get te days starting from Monday 23 May 2016 to Sunday 29 May 2016.

I have tried:

var startDate = moment().startOf('isoweek').year(year).month(month).day(day);
var endDate = moment().endOf('isoweek').year(year).month(month).day(day);
var weekDays = getWeekDays(startDate, endDate);

where the variable year, month and day are equals in this example to: 2016, 05, 24. This doesn't work. Do you have any suggestions using momentjs Or how to do it without using momentjs?


UPDATE

Ok I solved it myself! Sorry for the posted question, i put the solution here ( First check is the date is valid!):

if(moment(year + "/" + month + "/" + day, "YYYY/MM/DD", true).isValid()){
    var startDate = moment(year + "/" + month + "/" + day, "YYYY/MM/DD").startOf('isoweek');
    var endDate = moment(year + "/" + month + "/" + day, "YYYY/MM/DD").endOf('isoweek');
    var weekDays = getWeekDays(startDate, endDate);
}
2
You may answer the question yourself. Read : Self answerAni Menon

2 Answers

0
votes

This is what i did to solve the problem:

if(moment(year + "/" + month + "/" + day, "YYYY/MM/DD", true).isValid()){
    var startDate = moment(year + "/" + month + "/" + day, "YYYY/MM/DD").startOf('isoweek');
    var endDate = moment(year + "/" + month + "/" + day, "YYYY/MM/DD").endOf('isoweek');
    var weekDays = getWeekDays(startDate, endDate);
}

function getWeeDays(startDate, endDate) {
    "use strict";

    var days = [];
    var day = startDate;

    while (day <= endDate) {
        days.push(day);
        day = day.clone().add(1, 'd');
    }

    return days;
}
0
votes
`moment(anyValidDate).day()`
 // will return you the index of the day of given date.
//i.e. 0 for Sunday, 1 for Monday and so on till 6 for Saturday. list  of week days.

new Date().getDay() // will give same result as above.

next you know what to do.