Reputation: 2842
I’m trying to calculate the week number from the epoch time that I’m receiving from the backend. So the value that I receive from the backend is this 1571097600000(15th October 2019)
. Now when I change this epoch date to start of the week
using this code
moment(1571097600000).startOf("week").unix()*1000
what I get is this 1570906800000(13th October 2019)
. But when I format this date the week number is incorrect. This is how I’m formatting
moment.(1570906800000).format("W, YYYY")
The value that I get is 41
but actually the week number is 42
. Any idea what is going on over here
Here is the code that I'm using
console.log(moment(1571097600000).startOf("week").unix()*1000)
console.log(moment(1571097600000).startOf("week").format("W, YYYY"))
Upvotes: 0
Views: 376
Reputation: 147363
What is happening is that your system settings are for the start of week on Sunday, but ISO weeks start on Monday.
Your initial time value is for Tue 15 Oct 2019, however when you do startOfWeek, the date is set to Sun 13 Oct 2019, which is the previous ISO week. Moment.js claims to use "locale aware" start of week, however I don't know how robust that is. I'd suggest always using ISO weeks.
If you want to use ISO weeks, use startOf('isoWeek').
let mLocal = moment(1571097600000);
let mISO = mLocal.clone();
let f = 'ddd DD MMM YYYY';
console.log('Start date : ' + mLocal.format(f));
// "locale aware" start of week
mLocal.startOf("week");
// ISO start of week
mISO.startOf("isoWeek");
console.log('Local start: ' + mLocal.format(f));
console.log('ISO week : ' + mLocal.format("W, YYYY"))
console.log('ISO start : ' + mISO.format(f));
console.log('ISO week : ' + mISO.format("W, YYYY"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
Upvotes: 1