Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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_Sunday('20110604') is 20110529

The full backup is done on Sundays = weekly. If I want to restore daily backup I need full (weekly) and daily backup. I need to copy backup files before restoring to temp directory so I restoring daily backup I need to know what weekly backup file I need to copy along the daily file.

My thought was to get Julian representation (or something similar) for the given date and then subtract 1 and check if it is Sunday ... Not sure if this is the best idea and how to convert given date into something I can subtract.

like image 879
Radek Avatar asked May 16 '11 22:05

Radek


1 Answers

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.

like image 122
RobG Avatar answered Oct 21 '22 08:10

RobG