PHP获取日期时间差

PHP中我们常使用DateTime对象来获取日期和时间。那么如果我们想要求两个时间差呢?

一种办法显然是使用mktime()函数来获取两个日期或时间的Unix Timestamp,再求出两者的差,最后将Unix Stamp转化为时间:

//2017-03-31 14:25:00
$datetime_1 = mktime(14, 25, 0, 3, 31, 2017);
$now = mktime();

//$date_diff now contains the difference in seconds between //$datetime1 and $now
$date_diff = $now - $datetime_1;

而另外一种更方便的方法就是使用DataTime的diff函数:

//current time based on local machine's time zone setting
$datetime1 = new DateTime();

//2017-05-12 14:25:00
$datetime2  = new DateTime("2017-05-12 14:25:00");

//获取$datetime2 - $datetime1的时间差
$timediff = $datetime1->diff($datetime2);

注意:$datetime1->diff($datetime2)所返回的是一个DateInterval对象:

DateInterval {
    /* Properties */
    public integer $y ;
    public integer $m ;
    public integer $d ;
    public integer $h ;
    public integer $i ;
    public integer $s ;
    public integer $invert ;
    public mixed $days ;

    /* Methods */
    public __construct ( string $interval_spec )
    public static DateInterval createFromDateString ( string $time )
    public string format ( string $format )
}

若是获取的时间差为负,那么其中$invert的值为1,若为正,则$invert为0。而我们可以很方便地得到时间差:

//小时数差
$hourdiff = $timediff->h;
//分钟数差
$minutediff = $timediff->i;
//年份差
$yeardiff = $timediff->y;
...

另外DateInterval有一个很好用的函数format()

//将会以xx:xx的形式输出时间差(比如05:21,即相差5小时21分钟)
echo $timediff->format('%H:%I');

这样大大方便了输出的可读性。具体的format()函数格式如下:

Format CharacterDescriptionExample values
YYears, numeric, at least 2 digits with leading 001, 03
yYears, numeric1, 3
MMonths, numeric, at least 2 digits with leading 001, 03, 12
mMonths, numeric1, 3, 12
DDays, numeric, at least 2 digits with leading 001, 03, 31
dDays, numeric1, 3, 31
aTotal number of days as a result of a DateTime::diff() or (unknown) otherwise4, 18, 8123
HHours, numeric, at least 2 digits with leading 001, 03, 23
hHours, numeric1, 3, 23
IMinutes, numeric, at least 2 digits with leading 001, 03, 59
iMinutes, numeric1, 3, 59
SSeconds, numeric, at least 2 digits with leading 001, 03, 57
sSeconds, numeric1, 3, 57
RSign “-” when negative, “+” when positive-, +
rSign “-” when negative, empty when positive-,
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值