6

In my case, I receive a date in YYYY-mm-dd format. I want to get its week number as an output (first day of the week being Monday instead of Sunday):

    //This exact day is Sunday and the week number should be '1' - I get '2' instead

    var date = '2016-01-03' 
    var dateSplit = date.split('-')
    var weekNumber = moment(
    [dateSplit [0],
    dateSplit [1] - 1,
    dateSplit [2]]).week()

    console.log(weekNumber) --> returns '2'
Lukas
  • 151
  • 1
  • 8
  • See [Customize ->First Day of Week and First Week of Year](https://momentjs.com/docs/#/customization/dow-doy/) to learn how to change first day of the week (example [here](https://stackoverflow.com/q/45774927/4131048), [here](https://stackoverflow.com/q/38133313/4131048) and [here](https://stackoverflow.com/q/31495226/4131048)). Usually setting a locale should fix your issue. – VincenzoC Sep 05 '19 at 06:45

1 Answers1

16

Add this to your code

moment.updateLocale('en', {
  week: {
    dow : 1, // Monday is the first day of the week.
  }
});

moment.updateLocale('en', {
  week: {
    dow: 1, // Monday is the first day of the week.
  }
});

dateList = [
  moment("2016-01-02", "YYYY-MM-DD"),
  moment("2016-01-03", "YYYY-MM-DD"),
  moment("2016-01-04", "YYYY-MM-DD"),
  moment("2016-01-05", "YYYY-MM-DD"),
  moment("2016-01-06", "YYYY-MM-DD"),
]

dateList.forEach((date) => console.log(`${date.format("YYYY-MM-DD")} is in week ${date.week()}`))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
PEPEGA
  • 2,214
  • 20
  • 37