简体   繁体   English

Javascript 日期:在 year_n+1 的第 1 周时返回到 year_n 的最后一周

[英]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) .最初,我得到了 2020 年这一周的周数,即第 43 周(Oct 19 2020 - Oct 25 2020)
I also have two buttons which serve as next and previous .我还有两个按钮用作nextprevious

When I click next button, the date changes to (Oct 26 2020, Nov 1 2020) as well as the week number to 44.当我单击next按钮时,日期更改为(Oct 26 2020, Nov 1 2020)以及周数更改为 44。
The same way goes to previous button.同样的方法去上previous按钮。 All is working almost fine, However, when I reach year 2021 , the week number becomes 1 of course.一切都几乎正常,但是,当我到达2021 ,当然周数变为 1。 and when I click previous again, it goes to the last week number of year 2021 instead of 2020.当我再次单击上一个时,它会转到2021而不是 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.我知道为什么没有回到2020年的最后一周,因为我只扣除了7天。

However, I can't figure out how to go back to the last week of 2020 when I click previous.但是,当我单击上一个时,我不知道如何回到 2020 年的最后一周。
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.更新:刚才,我注意到,当我在 2020 年的最后一周并单击下一步时,它不是转到“2021”,而是跳到“2022”……该死,我真的很讨厌在 javascript 上处理日期。

I concluded.我总结道。 using native javascript date is such a hassle, instead, I used momentjs.使用原生 javascript 日期太麻烦了,相反,我使用了 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.无需获取周数和年份。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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