A friend of mine has been struggling to format a date string he’s pulling out from a MySQL table. He’s just started learning PHP, so he’s still getting to grips with things.
When he came to me with his problem, I sent him a link to the date function, but he couldn’t understand the manual’s example. I can actually relate, because when I first started learning PHP, the manual didn’t make much sense to me.
The scenario
The date from the DB being pulled out is:
1 | $db_date = "2011-12-31"; // (yyyy-mm-dd) |
My friend wants it in the following format:
1 | $new_format_date = "12-31-2011"; // (dd-mm-yyyy) |
The solution
1 2 3 | $db_date = "2011-12-31"; $new_format_date = date("d-m-Y", $db_date); echo $new_format_date; |
If $db_date is not a proper time format, you will be returned with 01-01-1970. That means you will need to parse the $db_date variable into a Unix timestamp by using the strtotime function.
1 2 3 | $db_date = "2011-12-31"; $new_format_date = date("d-m-Y", strtotime($db_date)); echo $new_format_date; |
0 comments:
Post a Comment