最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Moment.js set week start on Monday - Stack Overflow

programmeradmin0浏览0评论

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'

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'
Share Improve this question asked Sep 5, 2019 at 6:31 LukasLukas 1511 gold badge1 silver badge9 bronze badges 1
  • See Customize ->First Day of Week and First Week of Year to learn how to change first day of the week (example here, here and here). Usually setting a locale should fix your issue. – VincenzoC Commented Sep 5, 2019 at 6:45
Add a comment  | 

1 Answer 1

Reset to default 18

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>

发布评论

评论列表(0)

  1. 暂无评论