moment.js, how to get day of week number

前端 未结 5 738
臣服心动
臣服心动 2020-12-09 00:53

I have a moment date object, and want to get the selected day number (0-6) or (1-7).

I tried this, but it doesn\'t work

var aaa = moment(date).day();         


        
相关标签:
5条回答
  • 2020-12-09 00:57

    You can get this in 2 way using moment and also using Javascript

    const date = moment("2015-07-02"); // Thursday Feb 2015
    const usingMoment_1 = date.day();
    const usingMoment_2 = date.isoWeekday();
    
    console.log('usingMoment: date.day() ==> ',usingMoment_1);
    console.log('usingMoment: date.isoWeekday() ==> ',usingMoment_2);
    
    
    const usingJS= new Date("2015-07-02").getDay();
    console.log('usingJavaSript: new Date("2015-07-02").getDay() ===> ',usingJS);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

    0 讨论(0)
  • 2020-12-09 00:58

    From the docs page, notice they have these helpful headers

    http://momentjs.com/docs/#/get-set/weekday/
    (I didn't see them at first)

    With header sections for:

    • Date of Month
    • Day of Week
    • etc

    .

      var now = moment();
      var day  = now.day();
      var date = now.date(); // Number
    
    0 讨论(0)
  • 2020-12-09 01:06

    Define "doesn't work".

    const date = moment("2015-07-02"); // Thursday Feb 2015
    const dow = date.day();
    console.log(dow);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

    This prints "4", as expected.

    0 讨论(0)
  • 2020-12-09 01:08

    If you are specifically looking for the 1-7 approach...

    This is the ISO weekday number. moment.js has also taken this into account. Use isoWeekday()

    console.log(moment().isoWeekday()); // returns 1-7 where 1 is Monday and 7 is Sunday
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

    Seeing as I wrote this answer on a Tuesday, today this gives me a 2.

    0 讨论(0)
  • 2020-12-09 01:18

    I think this would work

    moment().weekday(); //if today is thursday it will return 4
    
    0 讨论(0)
提交回复
热议问题