drqn5418 2017-03-08 14:11
浏览 29
已采纳

too long

So I have an array of many images in it with their datetimes in the format Y-m-d H:i:s And I wish to find the number of days between the image's date and the current date. This is where I have reached till now...and I'm getting a new error for every small change I make.

$myDateTime = DateTime::createFromFormat('Y-m-d H:i:s', $current_time);
$currentDate = $myDateTime->format('Y-m-d');

foreach($all_images as $key => $am){

        $myDateTime1 = DateTime::createFromFormat('Y-m-d H:i:s', $am['datetime']);
        $imageDate = $myDateTime1->format('Y-m-d');

        $datediff=date_diff($currentDate,$imageDate);
        echo $datediff;
}

I'm getting this error: Warning: date_diff() expects parameter 1 to be DateTimeInterface, string given

Any help would be appreciated! Thanks a lot!

  • 写回答

1条回答 默认 最新

  • doujiangqu2823 2017-03-08 14:22
    关注

    What you've done is you've converted your values to Strings before comparing them, so it's no longer comparing the difference between two dates but instead the difference between two strings. This is your error cause.

    Solution:
    The values you pass to date_diff need to be two DateTime objects as per the manual:

    (PHP 5 >= 5.3.0, PHP 7)
    DateTime::diff -- DateTimeImmutable::diff -- DateTimeInterface::diff -- date_diff — Returns the difference between two DateTime objects

    Suggestion:

    foreach($all_images as $key => $am){
    
            $myDateTime1 = DateTime::createFromFormat('Y-m-d H:i:s', $am['datetime']);
            $imageDate = $myDateTime1->format('Y-m-d');
    
            $datediff=date_diff($myDateTime, $myDateTime1);
            echo $datediff->format('%R%a days'); // +2 days
    }
    

    Note that the above date_diff function takes Objects not strings.

    This will now use date_diff [procedurally in this example] to output a difference value $datediff which you can use with DateTime formatting to reach the number of days/hours/whatever. Please Read the manual.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线