-1

I want to generate a week array with day, month, year and day to string like:

Monday | 12-05-2014
Tuesday | 13-05-2014
Wednesday | 14-05-2014
Thursday | 15-05-2014
Friday | 16-05-2014
Saturday | 17-05-2014
Sunday | 18-05-2014

I want as week to start from Monday like the format from top.

I tried this but week does not start from Monday.

<?php $timestamp = time(); for ($day = 0 ; $day <= 7 ; $day++): ?>
  <tr>
    <th><?php echo date('D', $timestamp); ?></th>
    <th><?php echo date('d-m-Y', $timestamp); ?></th>
    <td><input type="checkbox" value="1" name="x"></td>
  </tr>
<?php $timestamp += 24 * 3600; endfor; ?>

I need to generate only a week with days from current month and last month and put all in array.

kablu
  • 629
  • 1
  • 7
  • 26
user3233336
  • 27
  • 1
  • 6
  • Hint: `date("D", 0) == "Thu"` ... `$time - abs($time % (60 * 60 * 24 * 7) - 60 * 60 * 24 * 7) - 60 * 60 * 24 * 10` – bwoebi May 16 '14 at 13:56
  • @bwoebi That's a whole lotta math! – John Conde May 16 '14 at 13:58
  • @JohnConde `$time - abs(($time + 86400) % 604800 - 604800) - 864000` ... better? :-P – bwoebi May 16 '14 at 14:03
  • @bwoebi lol, yes. Although if you really wanted to get fancy you can define constants that represent those values (i.e. `define('ONE_WEEK', 604800); define('ONE_DAY', 86400);`. Then humans who have to read it can save their brain for more important things like trying to figure out why my coffee mug is empty. ;) – John Conde May 16 '14 at 14:10
  • @JohnConde then I still prefer `const ONE_WEEK = 60 * 60 * 24 * 7;` – bwoebi May 16 '14 at 14:11
  • @bwoebi That works, too, because it is still only defined in one spot (and is readable to anyone who is wondering what the actual value is) – John Conde May 16 '14 at 14:13
  • 1
    using timestamps and a `ONE_WEEK` constant won't account for daylight savings time or leap years. – Oscar M. May 16 '14 at 14:20
  • @OscarM. leap years don't affect week days, only years when using modulo. and it's usually better to use UTC dates instead of daylight saving timezones, makes it actually mostly easier for the user to calculate the date in his timezone. – bwoebi May 16 '14 at 17:01
  • True, especially if granularity doesn't include actual times. Still, using the DateTime classes is much better because the code you end up writing is a lot easier to understand and parse. – Oscar M. May 16 '14 at 17:26

1 Answers1

7
$this_monday = new DateTime('Monday this week');
$next_monday = new DateTime('Monday next week');
$interval    = new DateInterval('P1D');
$datePeriod  = new DatePeriod($this_monday, $interval, $next_monday);
foreach($datePeriod as $day) {
    printf("%s | %s<br>\n", $day->format('l'), $day->format('d-m-Y'));
}

Demo

John Conde
  • 217,595
  • 99
  • 455
  • 496