上一篇:php获取某月第一个星期一的时间戳(2019-11-25 22:23:17)
文章大纲

php date_diff计算两个时间的时间差

2019-11-26 21:14:01

在计算时间间隔,自己想当然的直接写了如下代码:

$a = date_create("2019-11-11 10:10:10");
$b = date_create("2019-12-12 9:12:17");
echo date_diff($a, $b);

结果报Object of class DateInterval could not be converted to string的错误。

我还以为date_diff返回的就直接是相差的天数呢。


结果用var_dump一打印才知道返回的是一个对象,对象具体内容如下:

object(DateInterval)#3 (15) { 
    ["y"]=> int(0) 
    ["m"]=> int(1) 
    ["d"]=> int(0) 
    ["h"]=> int(23) 
    ["i"]=> int(2) 
    ["s"]=> int(7) 
    ["weekday"]=> int(0) 
    ["weekday_behavior"]=> int(0) 
    ["first_last_day_of"]=> int(0) 
    ["invert"]=> int(0) 
    ["days"]=> int(30) 
    ["special_type"]=> int(0) 
    ["special_amount"]=> int(0) 
    ["have_weekday_relative"]=> int(0) 
    ["have_special_relative"]=> int(0) 
}

相隔的年月日时分秒都有了,相隔的天数就是days这个属性,所以获取两个时间相隔多少天,就可以取这个days属性。

$c =date_diff($a, $b);
echo $c->days;


看网上,用的是format方法。

$c =date_diff($a, $b);
echo $c->format("%a days");


关于format格式,php手册里给了如下列举:

// '%y Year %m Month %d Day %h Hours %i Minute %s Seconds'      =>  1 Year 3 Month 14 Day 11 Hours 49 Minute 36 Seconds
// '%y Year %m Month %d Day'                                    =>  1 Year 3 Month 14 Days
// '%m Month %d Day'                                            =>  3 Month 14 Day
// '%d Day %h Hours'                                            =>  14 Day 11 Hours
// '%d Day'                                                     =>  14 Days
// '%h Hours %i Minute %s Seconds'                              =>  11 Hours 49 Minute 36 Seconds
// '%i Minute %s Seconds'                                       =>  49 Minute 36 Seconds
// '%h Hours                                                    =>  11 Hours
// '%a Days                                                     =>  468 Days


上一篇:php获取某月第一个星期一的时间戳(2019-11-25 22:23:17)
我要评论
评论列表