1

I've got the need to have an array of the dates Mon-Fri from a specific ISO week. I can't seem to find an inbuilt method that returns an array. I am using the DateTime class with the setISODate method as follows:

$bookingDate = new DateTime();
$bookingWeek = $bookingDate->setISODate($bookingDate->format("Y"), $bookingDate->format("W"));
$bookingDates = array();
$mon = $bookingDate->setISODate($bookingDate->format("Y"), $bookingDate->format("W"), 1);
array_push($bookingDates, $mon);
$tue = $bookingDate->setISODate($bookingDate->format("Y"), $bookingDate->format("W"), 2);
array_push($bookingDates, $tue);
$wed = $bookingDate->setISODate($bookingDate->format("Y"), $bookingDate->format("W"), 3);
array_push($bookingDates, $wed);
$thu = $bookingDate->setISODate($bookingDate->format("Y"), $bookingDate->format("W"), 4);
array_push($bookingDates, $thu);
$fri = $bookingDate->setISODate($bookingDate->format("Y"), $bookingDate->format("W"), 5);
array_push($bookingDates, $fri);
print_r($bookingDates);

However - the print_r of the array of dates returns each day as being Friday! Is there a way of achieving what I want?

davidkonrad
  • 83,997
  • 17
  • 205
  • 265
etoipi
  • 57
  • 4
  • Check my answer here http://stackoverflow.com/a/17065451/212940 – vascowhite Sep 22 '13 at 08:40
  • possible duplicate of [Calculating days of week given a week number](http://stackoverflow.com/questions/186431/calculating-days-of-week-given-a-week-number) – vascowhite Sep 22 '13 at 08:40

1 Answers1

1

You are changing the same DateTime instance ($bookingDate) and adding it to array. At the end each element of the array points to that same DateTime instance. And it contains the date that you set last. That is $fri

You need either different instances (depending on your need) or a formatted string in the array.

To create different instance add $bookingDate = new DateTime(); before each $bookingDate->setISODate function call. This will consume a lot or resource.

Its better to use a single DateTime instance and iterate over it.

for($i=0;$i<7;$i++){
    $year = intval($bookingDate->format("Y"));
    $week = intval($bookingDate->format("W"));
    $bookingDate->setISODate($year, $week, $i+1);
    $bookingDates[]=$bookingDate->format(DateTime::ISO8601);
}
print_r($bookingDates);

outputs

Array
(
    [0] => 2013-09-16T20:23:42+0600
    [1] => 2013-09-17T20:23:42+0600
    [2] => 2013-09-18T20:23:42+0600
    [3] => 2013-09-19T20:23:42+0600
    [4] => 2013-09-20T20:23:42+0600
    [5] => 2013-09-21T20:23:42+0600
    [6] => 2013-09-22T20:23:42+0600
)
Shiplu Mokaddim
  • 56,364
  • 17
  • 141
  • 187
  • An array of **string**'s - it does not matter OP wanted an array of **DateTime**'s, you think? Maybe not, but there _could_ be a very good reason for that. – davidkonrad Sep 22 '13 at 21:12
  • @davidkonrad obviously there could be a very good reason. Thats why I showed how to make an array of **DateTime**'s very first. – Shiplu Mokaddim Sep 23 '13 at 04:45