Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A respectable PHP Datetime parser

echo date('r',strtotime("16 Dec, 2010")); //Tue, 16 Dec 2008 20:10:00 +0530
echo date('r',strtotime("16 Dec  2010")); //Sat, 16 Jan 2010 00:00:00 +0530

That's just wrong... Either it should fail or it should parse correctly. Do you know any robust natural language date/time parser in php? How do you parse natural language date time in php?

Edit:

var_dump(strtotime("16 Dec, abcd")); //bool(false)

"16 Dec, 2010" is either a valid GNU date input format or it is not. In the first case it should return the correct answer and in the second it should return false. This is what I mean by 'wrong'.

Edit:

The purpose is as hop guessed to accept a significant variety of user input.

like image 583
anshul Avatar asked Dec 05 '25 08:12

anshul


1 Answers

If you know in what format the time is represented in the string, you can use strptime() together with the appropriate format string to parse it. It will at least report an error when it cannot interpret the string according to the format.

This function exists in PHP 5.1.0 and up.

If you want to take arbitrary user input, you should offer clear and obvious feedback to the user, so that she can do something about a falsely interpreted date. Most of the time, there won't be a problem anyway and you can't ever catch all problematic cases (think American vs. European format).


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!