Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moment.js set week start on Monday

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'
like image 998
Lukas Avatar asked Jan 26 '23 21:01

Lukas


1 Answers

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>
like image 141
PEPEGA Avatar answered Jan 28 '23 09:01

PEPEGA