fatkatie Posted February 17, 2017 Share Posted February 17, 2017 Without writing a regx, is there a php function/library that will take a string and try and convert it to a date? PHP's date is not adequate. For example, these are all "dates". I would expect it to succeed on any of these. On those that are ambiguous, there should be attribute that can be set like, expect year between 78 and 16. This is strictly best guess, I do not supply a format. Failure is expected. feb 21, 1999 Feburary 21, 1999 02/21/99 2/21/99 99/2/21 2-21-1999 19990221 sun, Feb 21, 1999 Sunday Feburary 21, 1999 anything returned by a mysql date (now(), datetime ...) Today's date is DATESTUFF You get the idea. Returns false on couldn't do it, and some array or seconds after N if successful. Thank you. Quote Link to comment Share on other sites More sharing options...
Solution Barand Posted February 17, 2017 Solution Share Posted February 17, 2017 (edited) Provided that you can spell "February", only two of those formats do not work $dates = [ 'feb 21, 1999', 'February 21, 1999', '02/21/99', '2/21/99', '99/2/21', '2-21-1999', '19990221', 'sun, Feb 21, 1999', 'Sunday February 21, 1999' ]; echo '<pre>'; foreach ($dates as $dstr) { printf("%-30s%-15s%s\n", $dstr, date('Y-m-d', strtotime($dstr)), strtotime($dstr)==0 ? 'X' : '' ); } Outputs feb 21, 1999 1999-02-21 February 21, 1999 1999-02-21 02/21/99 1999-02-21 2/21/99 1999-02-21 99/2/21 1970-01-01 X 2-21-1999 1970-01-01 X 19990221 1999-02-21 sun, Feb 21, 1999 1999-02-21 Sunday February 21, 1999 1999-02-21 For rogue formats you can always use DateTime::createFromFormat() Edited February 17, 2017 by Barand Quote Link to comment Share on other sites More sharing options...
fatkatie Posted February 18, 2017 Author Share Posted February 18, 2017 It's easy then to intercept those two then. I'll check the mysql output myself. Thanks for a very nice presentation. As for spelling, I can handle that too. 99% of the time it comes in a short feb. Quote Link to comment Share on other sites More sharing options...
Barand Posted February 18, 2017 Share Posted February 18, 2017 Best way is to sidestep the problem and use a datepicker component. Then you are not at the mercy of whatever format a user wants to enter. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.