Jump to content

Best guess date from messy string.


fatkatie
Go to solution Solved by Barand,

Recommended Posts

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.

Link to comment
Share on other sites

  • Solution

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 by Barand
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.