这将是正确的?(It's will be right ? for use operator for compare date on php?)

编程入门 行业动态 更新时间:2024-10-24 06:28:41
这将是正确的?(It's will be right ? for use < , > operator for compare date on php?)

这将是正确的? 使用< , >运算符比较日期在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' // false

The 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"; }

更多推荐

本文发布于:2023-07-23 18:30:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1235591.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:正确   这将是   operator   php   date

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!