本文介绍了用PHP遍历日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用PHP遍历日期.目前,我的代码陷入了重复110307的循环中.我需要日期格式为yymmdd.这是我试图使用的:

I am trying to loop through dates with PHP. Currently my code gets stuck in a loop repeating 110307. I need the date format to be in yymmdd. Here is what I was trying to use:

<?php
    $check_date = '100227';
    $end_date = '100324';

    while($check_date != $end_date){
        $check_date = date("ymd", strtotime("+1 day", strtotime($check_date)));
        echo $check_date . '<br>';  
    }
?>

推荐答案

strtotime将"100227"解释为今天的时间10:02:27,而不是2010-02-27.因此,第一步之后,$check_date(今天)为"110307".在所有后续步骤中,"110307"再次被解释为今天的时间,再次将$check_date赋予为"110307".

strtotime interprets "100227" as the time 10:02:27 today, not 2010-02-27. So after the first step, $check_date (today) is "110307". At all subsequent steps "110307" is again interpreted as a time today, giving $check_date as "110307" again.

迭代日期的一个巧妙技巧是利用mktime的日期归一化功能,如下所示:

A neat trick for iterating dates is to take advantage of mktime's ability to normalize dates, something like this:

$date_arr = array(27,2,2010);
$end_date = "100324";
do {
    $check_date = gmdate('ymd', gmmktime(0,0,0,$date_arr[1],$date_arr[0]++,$date_arr[2]));
    echo $check_date."\n";
} while($end_date!=$check_date);

这篇关于用PHP遍历日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 07:04