问题描述
||
好的,我有两个时间戳记以yyyymmdd格式保存在数据库中,分别是开始日期和结束日期。
说这些是我的开始日期和结束日期:20110618-20110630
我如何使其一直呼应20110618、20110619、20110620等到20110630?
解决方法
// Will return the number of days between the two dates passed in
function count_days( $a,$b ) {
// First we need to break these dates into their constituent parts:
$gd_a = getdate( $a );
$gd_b = getdate( $b );
// Now recreate these timestamps,based upon noon on each day
// The specific time doesn\'t matter but it must be the same each day
$a_new = mktime( 12,$gd_a[\'mon\'],$gd_a[\'mday\'],$gd_a[\'year\'] );
$b_new = mktime( 12,$gd_b[\'mon\'],$gd_b[\'mday\'],$gd_b[\'year\'] );
// Subtract these two numbers and divide by the number of seconds in a
// day. Round the result since crossing over a daylight savings time
// barrier will cause this time to be off by an hour or two.
return round( abs( $a_new - $b_new ) / 86400 );
}
// Prepare a few dates
$date1 = strtotime( \'20110618\' );
$date2 = strtotime( \'20110630\' );
// Calculate the differences,they should be 43 & 11353
echo \"<p>There are \",count_days( $date1,$date2 ),\" days.</p>\\n\";
$days = count_days($date1,$date2);
for ($i = 0; $i < $days; $i++) {
echo date(\'Ymd\',$date1+(86400*$i));
}
使用以下函数:获取两个日期之间的天数。
, 这应该在PHP 5.3上为您打印所有日期
$start = \'20110618\';
$end = \'20110630\';
$date = new DateTime($start);
$end = new DateTime($end)->getTimestamp();
while ($date->getTimestamp() <= $end) {
echo $date->format(\'Ymd\');
$date->add(new DateInterval(\'P1D\'));
}
, 使用PHP datetime对象,因此以下将是persudo代码
//Convert the 2 dates to a php datetime object
//Get the number of days differance inbetween
//For each day,//create a new datetime object,N days after the youngest object
//Echo the reasult out
, 您不能只是做类似的事情:
(已编辑以包括实际的php循环)
$date = new DateTime(\'20110618\');
do {
$d = $date->format(\'Ymd\') . \"\\n\";
echo $d;
$date->add(new DateInterval(\'P1D\'));
} while ($d < 20110630);