dongroufan6846 2015-11-06 06:21
浏览 74

条件DateDiff

I had visited some of the post retrieving the date difference between 2 dates in SO but it doesn't gave me the answer I was seeking. Same for reading the documentation, I had problem understanding how it works.

I have tried coding it but it doesn't behave like what I was expecting. Here is my code:

<?php
$currentDate = new DateTime();
$createDateJoin = date_create($getDate['date_joined']);
$dateJoin = date_format($createDateJoin, "Y-m-d");

$yearDifference = $currentDate->diff($createDateJoin);

  if ($yearDifference->d < 31 && $yearDifference->m = 0 && $yearDifference->y == 0) {
       echo $yearDifference->d . " days";
        } else if ($yearDifference->m > 3) {
              echo $yearDifference->m . " month";
        } else if ($yearDifference->y > 1) {
              echo $yearDifference->y . " years";
      } else {
              echo "Not yet assigned";
       }
 ?>

As you can see from my code above, I am trying to do a print when after calculating the difference between the 2 dates, it meets the condition of $yearDifference->.The behavior from the program that I have experienced does not print out the things I want accordingly (E.g Staff working more than 1 year will print out how many years they have work, months for those who just came in and new staff less than a month will print out days).

I would like to know how does ->d/m/y works and how can I actually make use of the d,m and y to draw out the specific date correctly. And I also noticed that when I treat $yearDifference as a String or int, it comes out different result for the conditions. So what should I treat the type to be to manipulate it more easily? Greatly appreciate the help.

  • 写回答

1条回答 默认 最新

  • dongyue5686 2015-11-06 06:50
    关注

    You can use this code to get the date different method diff() object returns more values to check you can print_r your object that will print all data member that are returned via diff() method

    <?php
    echo get_date_diff(strtotime('1990-10-12'),strtotime('2015-10-14'));
    function get_date_diff($date,$dateEnd) {
        $dStart = new DateTime(date("Y-m-d", $date));
        $dEnd = new DateTime(date("Y-m-d", $dateEnd));
        $dDiff = $dStart->diff($dEnd);
       return($dDiff->y.' years <br>'.$dDiff->m.' months <br>'.$dDiff->d. ' days');
    }
    
     ?> 
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?