Skip to content Skip to sidebar Skip to footer

The Closest Sunday Before Given Date With JavaScript

I need to know the date for last Sunday for given date in php & javascript Let's have a function give_me_last_Sunday give_me_last_Sunday('20110517') is 20110515 give_me_last_Su

Solution 1:

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.


Solution 2:

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

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

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


Solution 3:

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


Solution 4:

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;
}

Post a Comment for "The Closest Sunday Before Given Date With JavaScript"