简体   繁体   中英

Javascript date : go back to the last week number of year_n when on week number 1 of year_n+1

Initially, I got the number of week this week of month of 2020 which is week 43 (Oct 19 2020 - Oct 25 2020) .
I also have two buttons which serve as next and previous .

When I click next button, the date changes to (Oct 26 2020, Nov 1 2020) as well as the week number to 44.
The same way goes to previous button. All is working almost fine, However, when I reach year 2021 , the week number becomes 1 of course. and when I click previous again, it goes to the last week number of year 2021 instead of 2020.

My code for incrementing and decrementing weekly is this:

date.setDate(date.getDate()+7) //increment
date.setDate(date.getDate()-7) //decrement

I know the reason why it does not go back to the last week of 2020 because I only deducted 7 days.

However, I can't figure out how to go back to the last week of 2020 when I click previous.
Any idea?

UPDATE: Just now, I noticed, when I'm on the last week of 2020 and click next, Instead of going to '2021', It jumps to '2022'.. damn, I really hate working with dates on javascript.

I concluded. using native javascript date is such a hassle, instead, I used momentjs.

all of the long code simplified by using

moment(date).add/subtract(no_of_days, 'd');

It automatically do the thing for you. no need to get the number of week and the year.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM