PHP:如何在不使用strtotime函数的情况下添加一周?

时间:2015-01-23 08:33:01

标签: php datetime

我希望尽快回答我的疑虑。 :)所以这就是:我很难解决这个问题,如下所示:

$beg_week = "2014 - 49"; //yyyy - w
$stop_wk = "2015 - 5"
while($beg_week <= $stop_wk)
{
    /* do logic to add week in the format "yyyy - w", but also
     * have to consider the year */
    $beg_week = ''; 

}

那么,我怎样才能在一个“yyyy”中添加一个星期 - w&#39;格式,不使用strtotime()

3 个答案:

答案 0 :(得分:0)

  1. 使用date_parse_from_format()mktime()将您的开始和结束时间转换为时间戳。或者,如果从日期时间字段中检索数据,则使用MySQL UNIX_TIMESTAMP()之类的SQL函数。
  2. 使用date_parse_from_format()将日期分解为其组件。
  3. 使用mktime()获取时间戳
  4. 添加一周的秒数(60 * 60 * 24 * 7)
  5. 使用date()输出下周。
  6. 注意:如果2月份超过29天或28天(分别为跳跃或常规年份), date_parse*()将不会在返回的数组中记录/存储错误。这可能/可能无关紧要,具体取决于您使用它的目的。

答案 1 :(得分:0)

没有必要为此跳过带有date()和mktime()的箍。 DateTime类可以简单而干净地处理它,像这样{@ 3}}对你来说: -

$beg_week = (new \DateTime())->setISODate(2014, 49);
$stop_week = (new \DateTime())->setISODate(2015, 5);
$interval = new \DateInterval('P7D');

while($beg_week < $stop_week){
    echo $beg_week->format('Y-m-d') . "<br/>\n";
    $beg_week->add($interval);
}

答案 2 :(得分:-1)

很抱歉,我花了很长时间才能解决并分享我用于此事的方法/方法,因为我还有一个额外的项目。所以我做的是:

首先,构建一个获得一年最长周的函数(感谢@salathe),

function getIsoWeekYear($year)
{
    $date = new DateTime;
    $date->setISODate($year,53);
    return ($date->format("W") === "53" ? 53 : 52);
}

然后,考虑到给定年份,增加一周的值,

$beg_week = "2014 - 50";   //just a sample and not actually a string
$end_week = "2015 - 05";

while($beg_week<=$end_week)
(
    $out_data[] = $beg_week;

    $b_week_exp = explode(" - ",$beg_week);
    $b_yr_temp = $b_week_exp[0];
    $b_wk_temp = $b_week_exp[1];
    $max_wk_of_yr = getIsoWeeksInYear($b_yr_temp);

    $out_year = $b_yr_temp;
    $out_week_no = $b_wk_temp+1;
    if($out_week_no > $max_wk_of_yr)
    {
        $out_year = $b_yr_temp+1;
        $out_week_no = "1";
    }
    $beg_week = $out_year." - ".sprintf("%02s", $out_week_no);
)

那就是它,如果你要打印$ out_data,你将有一个数组,

2014 - 50
2014 - 51
2014 - 52
2015 - 01
2015 - 02
2015 - 03
2015 - 04
2015 - 05

嗯,这个逻辑就是我想要的,从$ beg_week到$ end_week的循环,因为它也是我在其中执行的逻辑。对于这个非常简单的问题,一个非常简单的技巧! :)对不起,有时我很迟钝,不回答我自己的问题/问题。我希望这个人能帮助那些也会遇到同样情况的人。谢谢!