Tuesday 14 August 2018

Breaking & Fixing Dates from MySQL to PHP

The way that databases store "date" field data is:


2008-11-19 // year - month - day
The way that us humans read dates (at least in the U.S.) is:

11-19-2008 // month - day - year
I write a lot of administrative panel modules that either display dates or, better yet, allow customers to their own dates for articles, events, etc. I've created a couple of PHP functions that allow me to easily handle the transition from MySQL to PHP and visa versa.

The PHP: MySQL to PHP
/* break a date */
function break_date($date)
{
$date = explode('-',str_replace('/','-',$date));
return $date[1].'-'.$date[2].'-'.$date[0];
}
The PHP: PHP to MySQL
/* fix a date */
function fix_date($date)
{
$date = explode('-',str_replace('/','-',$date));
return $date[2].'-'.$date[0].'-'.$date[1];
}
You'll see that I automatically replace "/" within the given date, break apart the date string, and rearrange the items to make the user and the database happy. Hopefully this saves someone some time!

0 comments:

Post a Comment