在 PHP 中减去日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3090067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 08:39:59  来源:igfitidea点击:

Subtracting dates in PHP

phpdatetimedatetimetimestamp

提问by aslum

Possible Duplicate:
How to calculate the difference between two dates using PHP?

可能的重复:
如何使用 PHP 计算两个日期之间的差异?

I have timestamps stored in the format YYYY-MM-DD HH:MM:SS(for example 2010-06-21 20:12:56). What would the best way to check how old the timestamp is? For the moment I am mainly interested in the number of days old.

我有以格式存储的时间戳YYYY-MM-DD HH:MM:SS(例如2010-06-21 20:12:56)。检查时间戳的最佳方法是什么?目前我主要对天数感兴趣。

回答by Michael Mrozek

You can use strtotimeto convert the string to a UNIX timestamp, which is in seconds. time()will give you the current UNIX timestamp. Subtract them to get how old the date is in seconds, and divide by 60*60*24to get it in days

您可以使用strtotime将字符串转换为 UNIX 时间戳,以秒为单位。time()将为您提供当前的 UNIX 时间戳。减去它们以获得以秒为单位的日期,然后除以60*60*24以天为单位

It's also doable using DateTime::diff, although I find the date functions easier than using the classes

使用DateTime::diff也是可行的,尽管我发现日期函数比使用类更容易

回答by Nguyen

$today = strtotime(date('Y-m-d H:i:s'));
$expireDay = strtotime($row['ExpireDate']);
$timeToEnd = $expireDay - $today;