the closest Sunday before given date with JavaScript

前端 未结 4 1237
旧时难觅i
旧时难觅i 2021-01-04 07:18

I need to know the date for last Sunday for given date in php & javascript

Let\'s have a function give_me_last_Sunday



        
4条回答
  •  半阙折子戏
    2021-01-04 07:37

    Based on Thomas' effort, and provided the input string is exactly the format you specified, then:

    function lastSunday(d) {
      var d = d.replace(/(^\d{4})(\d{2})(\d{2}$)/,'$1/$2/$3');
      d = new Date(d);
      d.setDate(d.getDate() - d.getDay());
      return d;
    }
    

    Edit

    If I were to write that now, I'd not depend on the Date object parsing the string but do it myself:

    function lastSunday(s) {
      var d = new Date(s.substring(0,4), s.substring(4,6) - 1, s.substring(6));
      d.setDate(d.getDate() - d.getDay());
      return d;
    }
    

    While the format yyyy/mm/dd is parsed correctly by all browsers I've tested, I think it's more robust to stick to basic methods. Particularly when they are likely more efficient.

提交回复
热议问题