views:

137

answers:

4

What is the best way in php to take the following string mm[some char]dd[some char]yyyy and translate it to yyyymmdd? I will probably want in the future, according to local do the same with dd[some char]mm[some char]yyyy.
If there is a way that already uses the Zend Framework API, the better

+2  A: 
<?php
$str = '08-24-1989'; // can be in any recognizable date format.    
$new_str = date('Ymd', strtotime($str)); // produces "20090824".
?>

You can replace Ymd in the second statement above with any date format characters found here.

If you're looking to use Zend's Zend_Date framework, check out some examples and documentation here. Quite frankly though, the PHP functions are a lot simpler and easier to use in your case.

James Skidmore
Be careful, when the month is lower than 12, i.e. the order of day and month isn't obvious, these functions can produce the wrong results. Just be careful and check a few dates :)
David Caunt
I find it's best to always stay with the Y-m-d format. That seems to always come out right.
smack0007
I agree with having the year then month then day (hours, minutes, seconds - Y-m-d H:i:s format). It is easier to _sort_ and _compare_.
wenbert
+1  A: 

date('Ymd', strtotime($time));

Strtotime is absolutely the best tool to translate almost any time format into a standard one that you can then use Date to put into the format you want.

Because you question title says MySQL Dates, this is the string format that mysql uses.

date('Y-m-d h:i:s', strtotime($time));

Chacha102
A: 

Unless [some char] varies , use the mysql str_to_date function, e.g. STR_TO_DATE('12|23|2009','%m|%d|%Y');

nos
A: 

I would absolutely use TIMESTAMP for any date storage. It's incredibly easy to handle time differences (like SELECT ... WHERE date BETWEEN 2138728753 AND 376251237) and can be translated to any locale pretty easily :)

Tomáš Fejfar
I usualy agrre with you. Except that this specific date is birth date. No manipulations are needed, except changing the order of the numbers.
Itay Moav
Ah, I see... yes, then it's better to do it using strtotime )
Tomáš Fejfar
Eh, no... :) I think that the timestamp is still better if you aim for easy localization. For example some eastern countries doesn't use gregorian calendar (@see http://en.wikipedia.org/wiki/Calendar#Currently_used_calendars). You will still need to convert the date to "machine readable format" (Y-m-d or so) and then convert it to the desired calendar ...
Tomáš Fejfar