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 t开发者_开发知识库able is structured as a timestamp and not a varchar,which is sometimes is.
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
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.
Take a look into strptime().
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...
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) );
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.
精彩评论