这将是正确的? 使用< , >运算符比较日期在PHP?
我测试了它。 这很好。 但我没有建立关于使用< , >运算符的比较日期在PHP的建议文件。
请告诉我可以使用< , >运算符来比较php上的日期吗?
<?PHP $today = "2010-10-19"; $expired = "2012-12-10"; if($expired > $today) { echo "not expired"; } else { echo "expired"; } ?>It's will be right ? for use < , > operator for compare date on php ?
I tested it. And it's work good. But i not founded documents for advice about use < , > operator for compare date on php.
Please tell me can we use < , > operator for compare date on php ?
<?PHP $today = "2010-10-19"; $expired = "2012-12-10"; if($expired > $today) { echo "not expired"; } else { echo "expired"; } ?>最满意答案
只要你的日期是可比较的格式,这将起作用。 由于它们是作为字符串进行比较的,因此您需要确保较大的日期组件是第一个,而较小的组件是最后一个。 例如,年份,然后是月份,然后是日期。 始终包含前导零。 这就是你在你的例子中所做的,所以它的工作原理。
如果您没有这种格式的日期,那么您的比较将在一段时间内失败。 例如:
'2016-07-04' > '2016-01-07' // true '04-07-2016' > '07-01-2016' // false比较日期的最佳方法是使用DateTime()因为DateTime对象具有可比性,并且还考虑了所有日期相关的事物,如闰年和DST。
<?PHP $today = new DateTime("2010-10-19"); $expired = new DateTime("2012-12-10"); if($expired > $today) { echo "not expired"; } else { echo "expired"; }As long as your dates are in a comparable format this will work. Since they are compared as strings you need to make sure that the larger dates components are first and the smaller ones last. For example, the year, then the month, then the date. Always include leading zeros. That's what you do in your example so it works.
If you do not have the dates in this format your comparison will fail some of the time. For example:
'2016-07-04' > '2016-01-07' // true '04-07-2016' > '07-01-2016' // falseThe best way to compare dates is with DateTime() as DateTime objects are comparable and also account for all things date related like leap year and DST.
<?PHP $today = new DateTime("2010-10-19"); $expired = new DateTime("2012-12-10"); if($expired > $today) { echo "not expired"; } else { echo "expired"; }更多推荐
发布评论