• support@answerspoint.com

Convert from one format to another in PHP

2137

how to convert date formate one to another.

1Answer


0

Here is the function i used for some of my projects where date format to be needed in different formats. What it does is, it takes the format you need from the format you have. It does check for which format the date is. ie, is it in mm/dd/YYYY or mm-dd-YYYY or YYYY-mm-dd format. You may add more formats if you would like to compare with other formats.

function dateFormat($format='m/d/Y', $inputFormat=NULL, $showTodayDate=true) {
    if(!is_null($inputFormat)){
        //$arrInputFormat = split
        if($inputFormat[2]=='/'){//mm/dd/YYYY format
            list($m,$d,$Y) = explode("/", $inputFormat);
        }
 
        if($inputFormat[2]=='-'){//mm-dd-YYYY format
            list($m,$d,$Y) = explode("-", $inputFormat);
        }
 
        if($inputFormat[4]=='-'){//YYYY-mm-ddd format
            list($Y,$m,$d) = explode("-", $inputFormat);
        }
        if(empty($inputFormat)){
            return '';
        }
 
        $time = strtotime("$Y-$m-$d");
    } else {
        //$inputFormat is empty
        if(!$showTodayDate){
            return '';
        } else {
            $time = time();
        }
    }
    return date($format, $time);
}

If the inputFormat is empty and showTodayDate is true then you get the today date in formatted date, else empty string. Empty string is because, if sometime we display date from DB table which is  null or empty.

  • answered 8 years ago
  • G John

Your Answer

    Facebook Share        
       
  • asked 8 years ago
  • viewed 2137 times
  • active 8 years ago

Best Rated Questions