PHP DateTime正则表达式 [英] PHP DateTime Regex
问题描述
长话短说,我继承了一些糟糕的代码。结果,由于日期格式的原因,在比较日期时,字符串比较是错误的。我试图将日期转换为有效的DateFormat语法,以便可以进行适当的比较。
Hey, long story short I have inherited some terrible code. As a result a string comparison is buggy when comparing dates due to the format of the date. I am trying to convert the date to a valid DateFormat syntax so I can run a proper comparison.
这些是当前格式的一些示例:
These are some samples of the current format:
12/01/10 at 8:00PM
12/31/10 at 12:00PM
12/10/09 at 5:00AM
等。我想将其转换为YYYYMMDDHHMM格式,即201012012000,以进行比较。如果有人可以给我一个快速的正则表达式片段来执行此操作,那将不胜感激,因为我现在正在为正则表达式打砖墙。我可以通过多次分解字符串来做到这一点,但是我宁愿以一种更有效的方式来做到这一点。
and so forth. I'd like to convert this to a YYYYMMDDHHMM format i.e 201012012000 for comparison purposes. If anyone can give me a quick regex snippet to do this that'd be appreciated as right now i'm hitting a brick wall for a regex. I can do it by exploding the string over several times etc but I'd rather do it in a more efficient manner.
谢谢!
推荐答案
使用 DateTime 类,它内置于PHP 5.3中。
Working with dates in strange formats is very easy with the DateTime class which was built into PHP 5.3.
不需要正则表达式或任何花哨的内容:
No need for regex or anything fancy:
$date = DateTime::createFromFormat('m/d/y \a\t g:iA', '12/10/09 at 5:00AM');
print_r($date);
一旦它是一个日期对象,就可以使用任何想要的格式。
Once it is a date object you can have it in any format you want.
这篇关于PHP DateTime正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!