Function to convert dates to and from Mysql


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. /**
  4. * function dateconvert
  5. *
  6. * dateconvert is a handy function to take the aches and pains out of mysqls stupidity
  7. * by converting data from a variable (posted from a form or just stored)
  8. * into a format mysql will be able to store and converting the
  9. * database date back into the british standard of date month year.
  10. * The Script accepts day.month.year or day/month/year or day-month-year.
  11. * example:
  12. *
  13. * <code>
  14. * <?php // using type 1
  15. * $date = "19.12.2005";
  16. * $date = dateconvert($date, 1);
  17. * echo $date; // Would echo 2005-12-19 which is the format stored by mysql
  18. * ?>
  19. * </code>
  20. * <code>
  21. * <?php // using type 2
  22. * $date = $row['date']; //your mysql date
  23. * $realdate = dateconvert($date,2);
  24. * echo $realdate; // would display 19/12/2005
  25. * ?>
  26. * </code>
  27. *
  28. * @author Chris McKee <[email protected]>
  29. *
  30. * @param string $date - Date to be converted
  31. * @param string $func - which function is to be used (1 for input to mysql, 2 for output from mysql)
  32. */
  33. function dateconvert($date,$func) {
  34. if ($func == 1){ //insert conversion
  35. list($day, $month, $year) = split('[/.-]', $date);
  36. $date = "$year-$month-$day";
  37. return $date;
  38. }
  39. if ($func == 2){ //output conversion
  40. list($year, $month, $day) = split('[-.]', $date);
  41. $date = "$day/$month/$year";
  42. return $date;
  43. }
  44.  
  45. }
  46.  
  47. ?>

URL: http://www.phpbuilder.com/annotate/message.php3?id=1031006

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.