Web Design Blog

This is where we store some of our Web Development thoughts, tips and tricks, just because we like to share.

PHP – Changing Date Format

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;

It’s as easy as that.
I hope that helps out someone else.

09 Mar 2011 / 1 Comment / PHP Scripts, Tips & Tricks / by Maruf

1 Comment

  1. Dean
    09/03/2011
    1

    Thanks mate,

    The friend.

Leave a Reply

© 2012 BrightCherry :)