Quantcast
Viewing all articles
Browse latest Browse all 7

Dealing with MySQL Date

Working with dates can be a pain, especially if you are storing them in a database. In the quick example you will learn the basics of the date, strtotime, and mktime functions to convert your dates to be stored in a MySQL database and to retrieve the date from the database and display it in a nice format for the end user to see.

Assuming you are using MySQL as your database, a data type of ‘date’ is stored as ‘YYYY-MM-DD’. In PHP we can represent the MySQL date data type by using the date() function like so.

echo date('Y-m-d'); //2010-10-02

To convert a stored date in a MySQL database to a user friendly format, use the strtotime() function to convert the date retrieved from the database into seconds. You will use this as the second parameter for the date() function that contains a string of how you want the date formatted. Check out the PHP manual’s date function page for a full list of what all the letter represent.

$db_date = '2010-10-02'; //MySQL date format
echo date('F j, Y', strtotime($db_date)); //October 2, 2010

When converting dates for entry into a database, you will likely collect the year, month, and date from a form as separate variables. If this is the case you can easily convert the variables into a MySQL ready date by using the mktime() function.

$year = 2010;
$month = 10;
$day = 2; //notice the 2 is not padded with a zero
$db_date = date('Y-m-d', mktime(0, 0, 0, $month, $day, $year));
echo $db_date; //2010-10-02

If you are using time in your code, the date function will handle time as well. The corresponding MySQL data type is “datetime”.

echo date('Y-m-d H:i:s'); //2010-10-02 00:32:15

Viewing all articles
Browse latest Browse all 7

Trending Articles