Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP function to get the date format?

I know how to use date format strings, to turn date('Y/m/d H:i:s'); into 2009/12/18 11:37:45.

I would like a function that can do the opposite - look at a formatted date then return the format. Is there one in PHP?

The reason is we have timestamps saved in our database in a variety of formats and I am writing a tool processing all of our old tables and analyzing the date entries.

EDIT: so I guess there isn't a straight-forward way to do this. I was thinking I could use strftime(), which returns the time in seconds since the epoch. So a better question is can I use that time in seconds in the timestamp fields in the mySQL database? I would guess this would work if the table is structured as a timestamp and not a varchar,which is sometimes is.

like image 720
tkotitan Avatar asked Feb 27 '23 22:02

tkotitan


1 Answers

No, there isn't such a function. You'll need to write a set of regular expression matches which express all the possible variations, e.g.

$variations = array (
    '^([0-9]{4})/[0-9]{2}/[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{4}2$' => 'Y/m/d H:i:s',
    // more here
);

foreach ($dateFromDatabase as $date) {
    foreach ($variations as $regexp => $dateFormat) {
        if (preg_match ('|' . $regexp . '|', $date)) {
            $matches[$dateFromDatabase] = $dateFormat;
            break;
        }
    }
}

// $matches now consists of an array of dates => format
like image 148
fooquency Avatar answered Mar 07 '23 01:03

fooquency