2

I am trying to find the closest previous Sunday to a date (unless date is Sunday).

So for example, if I have this array:

$dates = array(
    "2014-03-02 10:15:10", // sun
    "2014-03-03 12:15:10", // mon
    "2014-03-04 13:15:10", // tue
    "2014-03-05 10:15:10", // wed
    "2014-03-06 14:15:10", // thu
    "2014-03-07 18:15:10", // fri
    "2014-03-08 14:15:10", // sat
    "2014-03-09 14:15:10"  // sun
);

How can I efficiently output this:

$dates = array(
    "2014-03-02 00:00:00", // sun
    "2014-03-02 00:00:00", // sun
    "2014-03-02 00:00:00", // sun
    "2014-03-02 00:00:00", // sun
    "2014-03-02 00:00:00", // sun
    "2014-03-02 00:00:00", // sun
    "2014-03-02 00:00:00", // sun
    "2014-03-09 00:00:00"  // sun
);
user2217162
  • 897
  • 1
  • 9
  • 20
  • The question has been closed, but I was working on my answer: http://pastie.org/8912529 . It's different than all others – ItalyPaleAle Mar 12 '14 at 21:18
  • I think there's an easier method: `$date = new DateTime($dateFromYourArray);` `$date->modify(0 - $date->format('w') . ' day');` `$date->setTime(0, 0, 0);` – Jasper N. Brouwer Mar 12 '14 at 21:33

1 Answers1

2

Per this answer:

$date = date('Y-m-d', strtotime('last Sunday', strtotime($date)));

In your case:

$dates = array_map('find_sunday', $dates);

function find_sunday($date) {
    if (date('w', strtotime($date)) == 0) {
         return date('Y-m-d', strtotime($date));
    }
    return date('Y-m-d', strtotime('last Sunday', strtotime($date)));
}
Community
  • 1
  • 1
random_user_name
  • 25,694
  • 7
  • 76
  • 115