Monday, October 24, 2011

HOW TO convert date from a form post to another format in php for mysql use


One problem I have come across many times is accepting dates into a form field (perhaps on a cms backend) and needing to format it to another order or date layout to enter into mysql. Commonly since mysql accepts yyyy-mm-dd and I accept dates as mm-dd-yyyy the format needs to be changed from mm-dd-yyyy to yyyy-mm-dd in order for mysql to take it properly. Simply take $yourdate and convert it to $fdate with the php code below. You can change the array number order if you wanted to do something different.

To modify this for your purposes you will need to know what it is doing. First it is taking your dates and removing the pieces between the - in the explode function and then placing them into an array, reordering the array and imploding it (replacing it into a string) into the $fdate variable. Make sense? Any questions you have you can leave in the comments.

  1. $date = explode("-",$yourdate);
  2. if ($date[0]<=9) { $date[0]="0".$date[0]; }
  3. if ($date[1]<=9) { $date[1]="0".$date[1]; }
  4. $date = array($date[2], $date[1], $date[0]);
  5. $fdate=implode("-", $date);

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...
Web Design & Marketing - Click and get an instant quote on your project