setDate() set the wrong date on 31st?

后端 未结 4 1863
刺人心
刺人心 2021-01-15 04:12

This is very weird I don\'t know what I\'m doing wrong. I have a function to grab the date (i.e in this format: 06/24/2011), here\'s the function:



        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-15 04:47

    Right hierarchy is set year, then Month and at last add the Day. This will return the exact date that you added.

    function checkDate() {
    
      //Wrong order-  will return 1 May 2016
      var start = new Date();
      start.setDate(31);
      start.setMonth(4);
      start.setFullYear(2016);
      alert(start)
    
    
      //Right  order - will return 31 May 2016
      var end = new Date();
      end.setFullYear(2016);
      end.setMonth(4);
      end.setDate(31);
      alert(end)
    
    
    }

    This is the right heirarchy to set date.

提交回复
热议问题