Indrajeet Latthe
Indrajeet Latthe

Reputation: 384

get start and end day of week by year, month and week number

Goal

I want to get start day and end day by giving year, month and week number. I'm trying to use momentjs as it was already in my dependency.

Work I've done

It seems it's not possible if I set .month(monthInNumber) as I don't get Monday and it messes up so what I've done is naive way which is not working = 4*month and set it up as week.

getStartDateByWeekAndYear = function(week, year, month) {
    return moment().day("Monday").year(year).week((4*month)+(week)).toDate();
};

For last day(I want Satruday as last day and not Sunday)

getLastDateByWeekAndYear = function(week, year, month) {
    return moment().day("Saturday").year(year).week((4*month)+(week)).toDate();
};

I also tried couple of solutions but it seems it's not working If I try to implement same in my functions above.

Expected Output

getStartDateByWeekAndYear(2, 2019, 6)

I should get Monday, 3 June 2019 which is Today's date

getEndDateByWeekAndYear(2, 2019, 6)

I should get Saturday, 8 June 2019 which is this week's Saturday

Upvotes: 2

Views: 269

Answers (1)

VincenzoC
VincenzoC

Reputation: 31482

You can get that start of a given month/year using moment({Object}) and then get your desired week, by adding weeks using add().

Here a live sample:

const getStartDateByWeekAndYear = function(week, year, month) {
    return moment({y: year, M: month-1, d: 1})
      .add(week-1, 'w').day("Monday").toDate();
};

const getEndDateByWeekAndYear = function(week, year, month) {
    return moment({y: year, M: month-1, d: 1})
      .add(week-1, 'w').day("Saturday").toDate();
}

console.log( getStartDateByWeekAndYear(2, 2019, 6) );
console.log( getEndDateByWeekAndYear(2, 2019, 6)  );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

Upvotes: 2

Related Questions