在PHP中比较两个ISO8601日期字符串 [英] Comparing two ISO8601 dates strings in PHP

查看:119
本文介绍了在PHP中比较两个ISO8601日期字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要比较(实际上是排名/排序)PHP脚本中的日期.日期为ISO-8601日期格式,即

I need to compare (actually rank/sort) dates in a PHP script. The dates are ISO-8601 Date format i.e.

YYYY-MM-DD

我写了一个比较函数,该函数将日期分开并按年/月/日进行比较.但是,这似乎有点过头了,我可以轻松地完成一个简单的字符串比较,例如:

I wrote a comparison function which splits the dates and compares by year/month/day. However, it seems this may be overkill and I could just as easily done a simple string comparison like:

if ($date1 < $date2)
   // do something
elseif( $date1 > $date2)
   //do something else
else
   //do yet another thing

我对(ISO-8601)日期字符串比较的假设是否正确-即我可以放弃我的功能(在服务器上节省几个时钟周期),还是在自定义函数中明确进行比较是否更安全?

Is my assumption about (ISO-8601) Date string comparison correct - i.e. can I get rid of my function (to save a few clock cycles on the server), or is it safer to explicity do the comparison in a custom function?

推荐答案

http://en.wikipedia.org/wiki/ISO_8601#General_principles

日期和时间值的排列顺序从最高到最低:年,月(或周),日,时,分,秒和秒的一部分.因此,表述的字典顺序对应于时间顺序,但涉及负年的日期表述除外.这样就可以通过文件系统对日期进行自然排序.

Date and time values are organized from the most to the least significant: year, month (or week), day, hour, minute, second, and fraction of second. The lexicographical order of the representation thus corresponds to chronological order, except for date representations involving negative years. This allows dates to be naturally sorted by, for example, file systems.

继续进行字符串排序.如果维基百科还不够,那么 http://www.ietf.org/rfc/rfc3339.txt 肯定是,在那里搜索strcmp.

Go ahead with string sorting. If wikipedia is not enough, then surely http://www.ietf.org/rfc/rfc3339.txt is, search for strcmp in there.

这篇关于在PHP中比较两个ISO8601日期字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆