简体   繁体   中英

moment JS get correct week number of first week of year

I use this script to get a unique reference for a week in my app: moment().format(YWW) witch, today echo 201947 (4 first digit = year of week, 2 last digits = week number). it work great until now.

but I've a problem with the last week of 2019 / first week of 2020: The week start at 2019-12-30 but it's the first week of 2020 (with my code, i except 202001) but my code moment("2019-12-30").format('YWW'); return 201901, the week number is correct. but not the year (probably because the date of the day is in 2019).

How to update my code to obtain the correct year with my week number?

thanks

Use the GGGG format code for the ISO 4 digit week year:

 console.log(moment("2019-12-30").format('GGGGWW'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js" integrity="sha256-4iQZ6BVL4qNKlQ27TExEhBN1HFPvAvAMbFavKKosSWQ=" crossorigin="anonymous"></script>

According to this GitHub issue this bug won't be fixed. So, the solution is adding endOf('week') before formatting:

 console.log(moment("2019-12-30").endOf('week').format('YWW'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js" integrity="sha256-4iQZ6BVL4qNKlQ27TExEhBN1HFPvAvAMbFavKKosSWQ=" crossorigin="anonymous"></script>

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