1

I'm trying to figure out how can I get the the first day of week for the last 6 months and can't get to a working solution.

If I write date("Y-m-d 00:00:00", strtotime("-1 week", date("Y-m-d")); It just subtracts 7 days from the current date; what I want to do is to always return the date of Monday from that week.

Expected result:

2011-8-8 00:00:00
2011-8-1 00:00:00
2011-7-25 00:00:00
2011-7-18 00:00:00
etc
Joe Doyle
  • 6,363
  • 3
  • 42
  • 45
  • Im not going to really say much except http://www.php.net/manual/en/function.strtotime.php. Come on now. There are multiple examples with this type of thing right there. – Matt Aug 18 '11 at 09:48
  • see http://stackoverflow.com/questions/1897727/get-first-day-of-week-in-php – Mat Aug 18 '11 at 09:49
  • Who downvoted? The question is well-formed and perfectly valid. (Though, @Georges, you should have shown us what you tried and what went wrong.) – Lightness Races in Orbit Aug 18 '11 at 09:56
  • http://stackoverflow.com/questions/23563796/repeat-week-days-events-like-google-calender friends any idea for this question – Steve Bals May 12 '14 at 05:25

3 Answers3

4

This should do it:

for ($i=0; $i<52/2; $i++)
echo date('Y-m-d', mktime(1, 0, 0, date('m'), date('d')-date('w')-$i*7+1, date('Y'))) . " 00:00:00\n";

it's slightly changed from Mike's Post, who wants the sunday instead of the monday.

Lars
  • 5,757
  • 4
  • 25
  • 55
2

I'd recommend DateTime::createFromFormat.

Pre-PHP 5.3, you can use strtotime instead:

<?php
define('NUM_WEEKS', 10);

$dates = Array();
$dates[] = strtotime('Monday');

for ($i = 0; $i < NUM_WEEKS-1; $i++)
    $dates[] = strtotime('-1 week', $dates[$i]);

foreach ($dates as $date)
    echo strftime('%c', $date) . "\n";
?>

Output:

Mon Aug 22 00:00:00 2011
Mon Aug 15 00:00:00 2011
Mon Aug  8 00:00:00 2011
Mon Aug  1 00:00:00 2011
Mon Jul 25 00:00:00 2011
Mon Jul 18 00:00:00 2011
Mon Jul 11 00:00:00 2011
Mon Jul  4 00:00:00 2011
Mon Jun 27 00:00:00 2011
Mon Jun 20 00:00:00 2011

Live demo.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
2

If you're trying to make Saturday (or any other day for that matter) the first day of the week to select datasets, here's a good workaround:

<?php  $last_sat=date("z", strtotime("last Saturday")); 
$second_last_sat=date("z", strtotime("last Saturday-1 week"));  ?>

source: http://www.php.net/manual/en/function.strtotime.php

What you'd probably want is

<?php  $last_mon=date("z", strtotime("last Monday ")); 
$second_last_mon=date("z", strtotime("last Monday-1 week"));  ?>

etc..

ransom bot
  • 320
  • 1
  • 5