【问题标题】:Parameterizing php code with DatePeriod, DateInterval classes使用 DatePeriod、DateInterval 类参数化 php 代码
【发布时间】:2010-08-05 15:23:44
【问题描述】:

我不太了解 DatePeriod、DateInterval 类。这个问题与另一个问题有关 - How to display converted time zones in a 'generic week' (Sunday thru Saturday)? 我想参数化 artefacto 提供的解决方案。

我们将不胜感激!

这是artefacto的代码:

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

这是我想出的:

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)
    );
    ...

正如 artefacto 指出的那样,“从两次构建 DatePeriod 只是为了让它在这两个日期之后立即分解是没有意义的”,但是我不明白如何轻松修改它以使其与其余日期一起工作他的代码(我猜它需要 $indiaAvail 存在......)

【问题讨论】:

    标签: php datetime time timezone


    【解决方案1】:

    DatePeriod 类存储开始日期、结束日期和间隔(或等效地,开始日期、间隔和重复次数)。它是Traversable,当在foreach 循环中迭代时,它将产生从开始到结束的所有日期(DateTime 对象),并以给定的间隔分隔它们。

    因此,迭代 DatePeriod 类与迭代由 DatePeriod 产生的所有日期组成的数组相同。

    所以我们可以这样写:

    //...
    $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
    );
    //...
    

    【讨论】:

    • 效果很好 - 很抱歉打扰您!
    猜你喜欢
    • 2014-12-26
    • 1970-01-01
    • 1970-01-01
    • 2013-01-07
    • 2014-02-25
    • 1970-01-01
    • 2012-07-24
    • 2022-01-10
    • 1970-01-01
    相关资源
    最近更新 更多