Efficient way to parse "ddmmyyyyThhmm" string to workable date string
I have the following types of strings:
17082011T1015
In other words: day month year T hours minutes
.
What would be an efficient way to parse th开发者_StackOverflow中文版ese strings in such a way that I end with something like a MySQL-like date:
`2011-08-17 10:15`
(There's no MySQL involved here by the way)
It's for Windows PHP < 5.3 so strptime()
and date_parse_from_format()
/DateTime::createFromFormat()
are NOT an option.
It's just rearranging a string.
$date = "17082011T1015";
$day = substr($date, 0, 2);
$month = substr($date, 2, 2);
$year = substr($date, 4, 4);
$hour = substr($date, 9, 2);
$minute = substr($date, 11, 2);
echo $year . '-' . $month . '-' . $day . ' ' . $hour . ':' . $minute;
I think I'll end up using this solution:
sscanf( '17082011T1015', '%02s%02s%04sT%02s%02s', $day, $month, $year, $hours, $minutes );
$datetime = $year . '-' . $month . '-' . $day . ' ' . $hours . ':' . $minutes;
Before asking the question I didn't realize I could utilize the optional arguments to sscanf()
to my advantage, and thought I would have to resort to something like this:
$parsed = sscanf( '17082011T1015', '%02s%02s%04sT%02s%02s' );
$datetime = $parsed[ 2 ] . '-' . $parsed[ 1 ] . '-' . $parsed[ 0 ] . ' ' . $parsed[ 3 ] . ':' . $parsed[ 4 ];
Not too bad either, but I like to be pretty clear as possible with named variables, so that it's obvious what this little routine does.
If you are using PHP >= 5.3.0, you may use DateTime::createFromTimeFormat to create ordinary DateTime
object from that string.
Should be something like:
$str = "17082011T1015";
$date = DateTime::createFromFormat($str,'DDMMYYYYThhII');
echo $date->format("Y-m-d H:i:s");
Can't test it here, only have PHP 5.2. But I think you could figure the right format yourself.
精彩评论