PHP Set format date

Just a function to change the format of a mysql date to the one you want to.

function setDate($L_date,$L_dateFormat="dd-mm-yyyy"){//sets a date in a format
	if(strlen($L_date)>0){
		$L_arrTemp = split(" ",$L_date);
		$L_strDate = $L_arrTemp[0]; // 2007-07-21 year month day
		$L_arrDate = split("-",$L_strDate);// split date 
		$L_strYear =  $L_arrDate[0];
		$L_strMonth = $L_arrDate[1];
		$L_strDay = $L_arrDate[2];
 
		if($L_dateFormat == 'yyyy-mm-dd'){//default
		    return $L_arrTemp[0];
        }
		elseif($L_dateFormat == "dd-mm-yyyy"){//day month year
			$returnDate = $L_strDay."-".$L_strMonth."-".$L_strYear;
			return $returnDate;
		}
		elseif($L_dateFormat == "mm-dd-yyyy"){//month day year
			$returnDate = $L_strMonth."-".$L_strDay."-".$L_strYear;
			return $returnDate;
		}
	}
	else return false;
}
Related Posts Related Websites
Help sharing and Flatter me ;)

Share

6 Comments

  1. Nenillo says:

    I think you can do the same this way:

    date(‘d-m-Y’,strtotime($indate));

  2. Chema says:

    I’ve forgot to say that is from mysql date to other format xD now i think it’s not the same, or it will work too?

  3. Nenillo says:

    Yes, it will work too, I’m using it everyday :)

  4. Chema says:

    mmmmmm Yes I see it works as you said, but the problem is when the input is like “dd-mm-yyyy” then the function date returns 1919-1212-09090909 for example.

    And for that script I needed to be able to do that xD

  5. Nenillo says:

    Yes, it only accepts “yyyy-mm-dd”, as your function do.

    You can also do:

    date(‘d-m-Y’,strtotime(implode(‘-’,array_reverse(explode(‘-’,$indate)))));

    But yeah, it becomes a little messy…

    I see you are using split function, is the same that “explode” but split is deprecated and will be removed on PHP6

  6. Chema says:

    Oh thanks on that one. I’ll change it now form OC…just for the future, thanks ;)

Leave a Reply

Follow me