【问题标题】:php strtotime first day of next month returns nothingphp strtotime 下个月的第一天什么都不返回
【发布时间】:2012-04-20 18:08:41
【问题描述】:

我一直在阅读有关 strtotime 和“下个月”问题的 php 问题。我想做的是两个日期之间的月份计数器。 例如,如果我有开始日期 01.02.2012 和停止日期 07.04.2012 我想获得返回值 - 3 个月。如果开始日期是 28.02.2012 和 07.04.2012,结果也是 3 个月。我没有计算确切的天数/月数,只是两个日期之间的几个月。使用一些奇怪的日期、mktime 和 strtotime 的用法并没有什么大不了的,但不幸的是,开始和停止日期可能在两个不同的年份,所以

mktime(0,0,0,date('m')+1,1,date('Y');

不会工作(我现在不知道年份,如果它在开始日期和停止日期之间发生变化。我可以计算出来,但它不是很好的解决方案)。完美的解决方案是使用:

$stat = Array('02.01.2012', '07.04.2012')
$cursor = strtotime($stat[0]);
$stop = strtotime($stat[1]);
$counter = 0;
    while ( $cursor < $stop ) {
   $cursor = strtotime("first day of next month", $cursor);
   echo $cursor . '<br>';
   $counter++;
   if ( $counter > 100) { break; } // safety break;
    }
    echo $counter . '<br>';

不幸的是 strtotime 没有返回正确的值。如果我使用它返回空字符串。 任何想法如何获得下个月第一天的时间戳?

解决方案

$stat = Array('02.01.2012', '01.04.2012');
$start = new DateTime( $stat[0] );
$stop = new DateTime( $stat[1] );
while ( $start->format( 'U') <= $stop->format( 'U' ) ) {
    $counter ++;
    echo $start->format('d:m:Y') . '<br>';
    $start->modify( 'first day of next month' );
}
echo '::' . $counter . '..<br>';

【问题讨论】:

  • 我不确定这是否会对您有所帮助,但问题可能出在本地,例如 02.01.2012 可能是 2 月 1 日和 1 月 2 日。

标签: php strtotime next


【解决方案1】:
<?php
$stat = Array('02.01.2012', '07.04.2012');
$stop = strtotime($stat[1]);
list($d, $m, $y) = explode('.', $stat[0]);
$count = 0;
while (true) {
    $m++;
    $cursor = mktime(0, 0, 0, $m, $d, $y);
    if ($cursor < $stop) $count ++; else exit;
}
echo $count;
?>

简单的方法:D

【讨论】:

  • 不幸的是,您的示例不起作用。我认为即使它是我自己发明东西的一个很好的基础,但我想它不是。现在使用 php5.3 中的 datetime 对象 - 希望找到解决方案
  • 没有错误,脚本什么也不返回。幸运的是我找到了解决方案 - 它在我的帖子中
猜你喜欢
  • 2017-08-03
  • 2013-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-09
  • 2011-12-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多