Home > Mobile >  moment.locale is causing wrong year
moment.locale is causing wrong year

Time:01-03

I've been using moment in my nodejs application since 2 years and it's working fine until yesterday 2022-01-01. moment started to give wrong year date (in server production and dev enviroment)

This is my code

const moment = require('moment'); 
console.log(moment().locale('fr').year(2021).week(48).startOf('week').format());
// ouptut 2020-11-23T00:00:00 01:00
console.log(moment().year(2021).week(48).startOf('week').format());
// output 2021-11-21T00:00:00 01:00

Here is my dev enviroment:

nodejs v10.23.0
npm 6.14.8
package: "moment": "^2.29.1",

CodePudding user response:

Can confirm this looks like a bug. Some quick investigation shows it looks like it is related to how the locale changes what the start of a week is, putting 2021's "first week" in 2020 and then rewinding, and I think the bug is reported here.

Basically this means you can't trust this mechanism to get to a time

Workaround

Use .add from a known-good value; e.g.

moment('2021-01-01').locale('fr').add(7 * 48, 'days').startOf('week').format();
// => '2021-11-29T00:00:00 00:00'

Notice how this still may be different to other locale week behaviour due to the "start of week" being different, in most of the world the week starts on "Monday" but in some places (e.g. the USA) Sunday is the first day of the week

moment('2021-01-01').add(7 * 48, 'days').startOf('week').format();
// => '2021-11-28T00:00:00 00:00' (USA-style default behaviour)

Consistency

If you don't want this behaviour to change over locales at all, rather than using the "start of the week" you need to pick the day specifically, i.e. 1 = Monday

const usa = moment('2021-01-01').add(7 * 48, 'days').day(1).format();
const fr = moment('2021-01-01').locale('fr').add(7 * 48, 'days').day(1).format();
usa === fr; // true, both 29th of November
  • Related