Forum Moderators: coopster

Message Too Old, No Replies

Date converting

         

ramoneguru

4:23 am on Apr 22, 2005 (gmt 0)

10+ Year Member




I am retrieving a date from mysql (using the mysql date format YYYY-MM-DD format). Is there an easy way to convert a date in that format:
YYYY-MM-DD
to this format:
MM-DD-YYYY

I've seen a few online, but they all involve ridiculous regular expressions....
--Nick

ironik

4:32 am on Apr 22, 2005 (gmt 0)

10+ Year Member



Regular expressions are powerful way of enacting on data patterns, but if you wanted to convert it without a regex you could try:

$date = '2005-04-15';
$parts = explode('-', $date);
$newDate = $parts[1] . '-' . $parts[2] . '-' . $parts[0];

I think there might also be a way for MySQL to return a formatted date, but I'm not sure how that is achieved (I normally store them as a unix timestamp).

mattx17

5:25 am on Apr 22, 2005 (gmt 0)

10+ Year Member



Actually, you can do this with a regex, but it doesn't have to be ridiculous.

$Date = '2005-12-21';
$DateParts = preg_split('#\-¦\/¦\.#',$Date);
$NewDate = $DateParts[1] . "-" . $DateParts[2] . "-" . $DateParts[0];

Basically it will split any date into parts if it's separated by /, - or .

dreamcatcher

7:57 am on Apr 22, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



If you are pulling your data from MySQL let MySQL do the work for you by using DATE_FORMAT:

$query = mysql_query("SELECT *,DATE_FORMAT(date, '%m-%d-%Y') as date_string FROM table") or die(mysql_error());

$row = mysql_fetch_object($query);

echo $row->date_string;

or if you use fetch_array of fetch_assoc use $row['date_string']

dc

ramoneguru

11:07 pm on Apr 22, 2005 (gmt 0)

10+ Year Member



Cool, all of those work. I like the mysql style, but I think its time I start working more with regular expressions. Thanks everyone.
--Nick

coopster

2:32 am on Apr 27, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Put the work on the database if at all possible. Regex's are cool, but they demand a lot from the server.

<added>
Granted it may not be too noticeable, but just knowing stuff like this comes in handy when you get into performance tuning.
</added>