views:

28

answers:

1

Hi,

I dont understand DatePeriod, DateInterval classes very well. This question is linked to another one - http://stackoverflow.com/questions/3386952/how-to-display-converted-time-zones-in-a-generic-week-sunday-thru-saturday wherein I want to parameterize the solution offered by artefacto.

Help would be appreciated!

This is artefacto's code:

$tz1 = new DateTimezone("Asia/Calcutta");
$indiaAvail = array(
    new DatePeriod(new DateTime("2010-08-01 10:00:00", $tz1),
        new DateInterval("PT2H15M"), 1)
);

This is what I came up with:

function shift_timezones_onweek($from_timezone, $from_timebegin, $from_timeend, $to_timezone)
{

    $tz1 = new DateTimezone($from_timezone);

    $datetime1 = new DateTime("2010-08-01 $from_timebegin", $tz1);
    $datetime2 = new DateTime("2010-08-01 $from_timeend", $tz1);

    $interval = $datetime1->diff($datetime2);

    $indiaAvail = array(
        new DatePeriod($datetime1, $interval, 1)
    );
    ...

As artefacto points out, "there's no point in building a DatePeriod from two times just to have it decomposed immediately after into those two dates", however I dont understand how I can modify this easily to make it work with the rest of his code (which requires the $indiaAvail to exist as it is I guess...)

A: 

The DatePeriod class stores a start date, an end date and an interval (or, equivalently, a start date, an interval and a number of repetitions). It is Traversable, and when iterated in a foreach loop, it will yield all the dates (DateTime objects) from the start to the end, with the given interval separating them.

Therefore, iterating a DatePeriod class is the same as iterating an array composed of all the dates that would be yielded by DatePeriod.

So we can write:

//...
$tz1 = new DateTimezone($from_timezone);

$datetime1 = new DateTime("2010-08-01 $from_timebegin", $tz1);
$datetime2 = new DateTime("2010-08-01 $from_timeend", $tz1);

$indiaAvail = array(
    array($datetime1, $datetime2),
);


$tz2 = new DateTimezone($to_timezone);
//convert periods:
$times = array_map(
    function (array $p) use ($tz2) {
       $res = array();
       foreach ($p as $d) {
           $res[] = $d->setTimezone($tz2);
       }
       return $res;
    },
    $indiaAvail
);
//...
Artefacto
Works marvelously - sorry for bothering you with this!
DrMHC