Jeenal Infotech

Change user date into mysql date format

Lots of time we face problem to store the date into mysql database because of its default format i.e YYYY-mm-dd. So we have to change that date format either in php or Mysql before storing it into database. There are various ways to convert date format but we are going to use php date() and strtotime() to achieve our target.

Here we go 🙂

 * @param type $date integer or string
 * @param type $dateOnly boolean 
 * @param type $format string 
 * @return type string 

function dateConvertToDB ( $date , $dateOnly = false , $format = "Y-m-d" ) {
//if passed date is integer then need to convert it into unix timestamp using strtotime() 

    if ( is_int ( $date ) ) {
        $timestamp = $date ;
    } else {
       $timestamp = strtotime ( $date ) ;
    if ( !$dateOnly )

        $format.=" H:i:s" ;

    return @date ( $format , $timestamp ) ;



We can write date in different format but in php usually we follow either American (m/d/y) or European (d-m-y) format. while converting date format the date sequence i.e day, month and year and the separator (i.e slash, hyphen and dot) play the crucial role.

If we are using American date format we can directly pass date in this mm/dd/yyyy format.

If we pass date in this mm-dd-yyyy format, we have to replace the hyphen (-) with slash(/).

To get the correct output : Add $date = str_replace ( ‘-‘ , ‘/’ , $date ) before $timestamp = strtotime ( $date ) ; in above code snippet.

Vise-versa, for European date format we can directly pass the date in this dd-mm-yyyy format.

If we pass date in this dd/mm/yyyy, we have to replace the (/) with (-).

To get the correct output: Add $date = str_replace ( ‘/’ , ‘-‘ , $date ) before $timestamp = strtotime ( $date ) ;

Leave a Reply

Your email address will not be published. Required fields are marked *

Show Buttons
Hide Buttons