dongpo2002 2015-07-15 07:32
浏览 19
已采纳

在每个循环上重置DateTime对象[关闭]

With the code below I get this results

2015-07-15 10:26:12 2015-08-15 10:26:12

2015-08-15 10:26:12 2015-09-15 10:26:12

2015-09-15 10:26:12 2015-10-15 10:26:12

2015-10-15 10:26:12 2015-11-15 10:26:12

Here is what I want to get as result

2015-07-15 10:26:12 2015-08-15 10:26:12

2015-08-15 10:26:12 2015-08-15 10:26:12

2015-07-15 10:26:12 2015-08-15 10:26:12

2015-08-15 10:26:12 2015-08-15 10:26:12

for ($i = 0; $i < 10; $i++) {
   echo  $time->format('Y-m-d h:i:s') . $time->modify('+1 month')->format('Y-m-d h:i:s'); 
}

So is it possible to reset datetime object on every loop?

  • 写回答

1条回答 默认 最新

  • dougu8742 2015-07-15 07:41
    关注

    You could use DateTimeImmutable instead of DateTime.
    When you call DateTimeImmutable::modify the instance isn't modified but a new istance with the modified values is returned.

    <?php
    $time = new DateTimeImmutable('07/15/2015 10:26:12');
    
    for ($i = 0; $i < 10; $i++) {
        echo  $time->format('Y-m-d h:i:s'), ' ', $time->modify('+1 month')->format('Y-m-d h:i:s'), "
    ";
    }
    

    prints

    2015-07-15 10:26:12 2015-08-15 10:26:12
    2015-07-15 10:26:12 2015-08-15 10:26:12
    2015-07-15 10:26:12 2015-08-15 10:26:12
    2015-07-15 10:26:12 2015-08-15 10:26:12
    2015-07-15 10:26:12 2015-08-15 10:26:12
    2015-07-15 10:26:12 2015-08-15 10:26:12
    2015-07-15 10:26:12 2015-08-15 10:26:12
    2015-07-15 10:26:12 2015-08-15 10:26:12
    2015-07-15 10:26:12 2015-08-15 10:26:12
    2015-07-15 10:26:12 2015-08-15 10:26:12
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改