PHP: date analysis of any format (especially: 2008-10-20, 2008/10/20, 2008.10.20, November 20/08)

strtotime("25/03/1957") returns false. What will satisfy all these date formats? I can’t imagine how long it will take to actually do my own, so I hope there is already one there that you know about.

thanks!

+4
source share
2 answers

I found that DateTime objects support a wider range of formats than the strtotime () function, and your server’s time zone settings also matter; but I ended up creating a function that would replace "/" with "-" before using the string-date methods. I also check for validity, then try replacing the visible dd and mm values ​​(03-25-2001 => 03-25-2001) if they are not valid before retesting.

+1
source

Given that some dates are valid, but can point to two different actual dates, no function can ever β€œguess” the correct format at any time ...

To help with this, a new function has been added with PHP> = 5.3: date_create_from_format - but it does not exist with PHP <5.3, unfortunately ...
(See also DateTime::createFromFormat )


However, in the example you took, 1957 is a possible source of problems: PHP usually works with UNIX timestamps when it comes to dates ...

And, at least on 32-bit systems, they can only represent dates between 1970 and 2038 , as they count the number of seconds since 1970-01-01.

To avoid this problem, it is often recommended to use the DateTime class, with which ( quoting ):

Information about the date and time is internally stored as a 64-bit number, therefore all conceivable dates (including negative years). the range is about 292 billion years in the past and also in the future.

(This will not solve the parsing problem with PHP 5.3, but it will solve the problem with dates ...)

+2
source

Source: https://habr.com/ru/post/1315973/


All Articles