tkotitan
tkotitan

Reputation: 3009

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.

Upvotes: 5

Views: 6295

Answers (6)

Alix Axel
Alix Axel

Reputation: 154613

Take a look into strptime().

Upvotes: 2

thetaiko
thetaiko

Reputation: 7834

Maybe its a better idea to save them all as unix timestamps then you can format them on the fly very easily depending on what your users want to see.

Upvotes: 0

qualbeen
qualbeen

Reputation: 1582

Yes, there does exist a function for this: strtotime()

strtotime — Parse about any English textual datetime description into a Unix timestamp

EDIT: Okay, the function might not return the formatting used, but you will get the timestamp, and then you're able to store it in any format.

Upvotes: 2

Galen
Galen

Reputation: 30170

You dont need to get the date into m/d/Y format. You can use strtotime to turn any valid date into any other date format you want.

date( 'format', strtotime($date) );

Upvotes: 0

gahooa
gahooa

Reputation: 137462

You could use regexp to identifiy specific date formats. You could add to your regexp list until you have 100% coverage.

if(preg_match('/^\d{4}\/\d{2}\/\d{2} \d{2}:\d{2}:\d{2}$/', $Date))
    $Format = 'Y/m/d H:i:s';

etc...

Upvotes: 0

fooquency
fooquency

Reputation: 1653

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

Upvotes: 5

Related Questions