the closest Sunday before given date with JavaScript

前端 未结 4 1207
旧时难觅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:30

    Ok so this is for JavaScript only. You have an input that you need to extract the month, date, and year from. The following is just partly an answer then on how to get the date:

    <script type="text/javascript">
    var myDate=new Date();
    myDate.setFullYear(2011,4,16)
    
    var a = myDate.getDate();
    var t = myDate.getDay();
    var r = a - t;
    document.write("The date last Sunday was "  + r);
    
    </script>
    

    So the setFullYear function sets the myDate to the date specified where the first four digits is the year, the next are is the month (0= Jan, 1= Feb.,...). The last one is the actually date. Then the above code gives you the date of the Sunday before that. I am guessing that you can add more code to get the month (use getMonth() method). Here are a few links that might be helpful

    • http://www.w3schools.com/js/js_obj_date.asp
    • http://www.w3schools.com/jsref/jsref_setFullYear.asp
    • http://www.w3schools.com/jsref/jsref_getMonth.asp

    (You can probably find the other functions that you need)

    I hope this helps a bit even though it is not a complete answer.

    0 讨论(0)
  • 2021-01-04 07:31

    Yup and strtotime has been ported to JS for eg http://phpjs.org/functions/strtotime:554 here.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-04 07:44

    final code (big thanks to @Thomas & @Rob)

    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());
    
      year = d.getFullYear()+'';
      month = d.getMonth()+1+'';
      day = d.getDate()+'';
      if ( month.length == 1 ) month = "0" + month; // Add leading zeros to month and date if required
      if ( day.length == 1 ) day = "0" + day;  
    
      return year+month+day;
    }
    
    0 讨论(0)
提交回复
热议问题