dongzhi5587 2013-09-06 15:08
浏览 14
已采纳

PHP:strtotime()提供错误的输出

In my script, I have a given end date. To get the start date, I subtract 23 months to the end date. Basically, what my script should do is to output 24 months (w/ year) - the last month/year to be printed should always be the specified end date.

For some reason, my script isn't returning my desired results. Given the $end = '2013-07-05', the script returns the result correctly. It prints out Aug 11 to Jul 13 which is correct.

But for some dates (e.g. $end = '2013-07-31'), the output is wrong. The result should be Sep 11 to Aug 13. But in this case, it outputs Aug 11 to Aug 13 which is absolutely wrong.

Here's my code:

<?php
$end = strtotime('2013-07-31 +1 month');
$date = strtotime('2013-07-31 -23 month');
$start = $month = $date;
$months = "";
while($month < $end)
{
     $months .= date('M y', intval($month))." ";
     $month = strtotime("+1 month", intval($month));
}
echo $months;
?>

I think there's something wrong with strtotime(). Thanks in advance.

  • 写回答

3条回答 默认 最新

  • dougui2254 2013-09-06 15:47
    关注

    Based on Marc B's answer I modified the script to deal with the 29,30,31 of each month. What I did was, if the date is 29, 30, or 31, it will be subtracted with 3 days so that the date will be either 28 or below and would work just fine with the current code that I have. It worked for me so I guess I'll just stick with this for now. Here's the updated code:

    <?php
    $dt = "2013-07-31";
    $dy = strtotime($dt);
    $day = date("d", $dy);
    
    if (($day == 29) || ($day == 30) || ($day == 31)){
         $dt = strtotime("$dt -3 days");
         $dt = date('Y-m-d', $dt);
    }
    
    $end = strtotime("$dt +1 month");
    $date = strtotime("$dt -23 month");
    $start = $month = $date;
    $months = "";
    while($month < $end)
    {
         $months .= date('M y', intval($month))." ";
         $month = strtotime("+1 month", intval($month));
    }
    echo $months;
    ?>
    

    Thanks for your help and insights. :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探