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 Character | Description | Example values |
---|---|---|
Y | Years, numeric, at least 2 digits with leading 0 | 01, 03 |
y | Years, numeric | 1, 3 |
M | Months, numeric, at least 2 digits with leading 0 | 01, 03, 12 |
m | Months, numeric | 1, 3, 12 |
D | Days, numeric, at least 2 digits with leading 0 | 01, 03, 31 |
d | Days, numeric | 1, 3, 31 |
a | Total number of days as a result of a DateTime::diff() or (unknown) otherwise | 4, 18, 8123 |
H | Hours, numeric, at least 2 digits with leading 0 | 01, 03, 23 |
h | Hours, numeric | 1, 3, 23 |
I | Minutes, numeric, at least 2 digits with leading 0 | 01, 03, 59 |
i | Minutes, numeric | 1, 3, 59 |
S | Seconds, numeric, at least 2 digits with leading 0 | 01, 03, 57 |
s | Seconds, numeric | 1, 3, 57 |
R | Sign “-” when negative, “+” when positive | -, + |
r | Sign “-” when negative, empty when positive | -, |