JavaScript for getting the previous Monday

后端 未结 7 2127
孤城傲影
孤城傲影 2021-02-19 04:03

I would like for the previous Monday to appear in the field where a user enters today\'s date.

E.g.: If today\'s date is entered 29-Jan-16 t

7条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-19 04:43

    Here is a fiddle demonstrating a few different formats: https://jsfiddle.net/umefez2j/3/

    function getMonday(d) {
      var m_names = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
      var d = new Date(d);
      var day = d.getDay(),
          diff = d.getDate() - day + (day == 0 ? -6:1); // adjust when day is sunday
    
      //Use this one to return this format: Mon Jan 25 2016 09:37:51 GMT-0600 (Central Standard Time)
      //return new Date(d.setDate(diff));
    
      //Use this one to return this format: Mon, 25 Jan 2016
      //monday=new Date(d.setDate(diff)).toUTCString();
      //monday=monday.split(' ').slice(0, 4).join(' ')
      //return monday;
    
      //Use this one to return this format: 25-Jan-2016
      monday=new Date(d.setDate(diff));
      var curr_date = monday.getDate();
      var curr_month = monday.getMonth();
      var curr_year = monday.getFullYear();
      return curr_date + "-" + m_names[curr_month] + "-" + curr_year;
    }
    
    alert(getMonday(new Date()));
    
    //Created with help from:
    //http://stackoverflow.com/a/27480352/3112803
    //http://stackoverflow.com/a/4156516/3112803
    //http://stackoverflow.com/a/27869948/3112803
    

提交回复
热议问题