DateTime::createFromFormat 在 PHP <5.3.0

2022-01-15 00:00:00 datetime format php date-format

我正在寻找一个与 DateTime::createFromFormat 但我需要它在运行早于 v5.3 的 PHP 版本的环境中工作.基本上我需要提供一种格式,就像你使用 Date() 函数,然后我需要针对该格式解析/验证字符串,如果字符串格式正确且日期有效,则返回时间戳.

I'm looking for a function identical to DateTime::createFromFormat but I need it to work in an environment running a version of PHP which is older than v5.3. Basically I need to provide a format, like you'd use with the Date() function, and I then need to parse/validate a string against that format, and return a timestamp if the string is formatted correctly and a valid date.

谁知道我在哪里可以找到类似的东西,还是我必须自己写?

Anyone know where I can find something like that, or do I have to write it myself?

同样,这必须使用作为参数提供的特定格式.格式可以是任何东西,所以不能保证我可以只使用 strtotime().

Again, this has to work with a specific format, provided as an argument. The format could be anything, so there's no guarantee I can just use strtotime().

推荐答案

DateTime::createFromFormatdate_parse_from_format 已添加到 PHP 5.3 中,因为对该功能的需求很高,尤其是为不使用美国日期/时间格式的用户编写代码的开发人员.

DateTime::createFromFormat and date_parse_from_format have been added in PHP 5.3 because there was a high demand for that feature, especially from developpers who code for users who don't use US date/time formats.


在此之前,您必须开发一个特定的函数来解析您使用的格式;与 PHP <5.3、一般做的是:


Before those, you had to develop a specific function to parse the format you were using ; with PHP < 5.3, what is generally done is :

  • 决定应用程序将接受哪种格式
  • 显示一些消息,例如 您的输入应该是 JJ/MM/AAAA" (DD/MM/YYYY 的法语)
  • 检查输入是否正确,关于该格式
  • 并解析它以将其转换为 PHP 可以理解的日期/时间.

这意味着应用程序和开发人员通常不允许使用那么多格式,因为每种格式都意味着一个不同的附加验证+解析功能.

Which means applications and developpers generally didn't allow for that many formats, as each format meant one different additionnal validation+parsing function.


如果你真的需要那种允许任何可能格式的函数,恐怕你必须自己写:-(


If you really need that kind of function, that allows for any possible format, I'm afraid you'll kind of have to write it yourself :-(

如果您了解 C 代码,也许看看 date_parse_from_format 的来源会有所帮助?它应该在 ext/date/php_date.c 之类的东西中——但似乎没有那么简单:它正在调用 timelib_parse_from_format 函数,该函数在 ext/data/lib/parse_date.c,看起来不太友好^^

Maybe taking a look at the sources of date_parse_from_format could help, if you understand C code ? It should be in something like ext/date/php_date.c -- but doesn't seem to be that simple : it's calling the timelib_parse_from_format function, which is defined in ext/data/lib/parse_date.c, and doesn't look that friendly ^^

相关文章