Posted By

jatkins on 03/21/11


Tagged

date format


Versions (?)

Convert YYYY-DD-MM dates to M d, Y format


 / Published in: PHP
 

Released into the public domain. Example: echo convert_dates('On 1969-07-20, the first Moon landing occurred. The crew returned to Earth on 1969-07-24. The last landing occurred on 1972-12-11.'); prints "On July 20, 1969, the first Moon landing occurred. The crew returned to Earth on July 24, 1969. The last landing occurred on December 11, 1972."

  1. <?php
  2. global $months;
  3. $months = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
  4. function convert_dates($text) {
  5. $date_regexp = '/([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})/';
  6. preg_match_all($date_regexp, $text, $dates);
  7. $dates = $dates[0];
  8. $new_dates = $dates;
  9. for($i=0;$i<count($new_dates);$i++) {
  10. $new_dates[$i] = explode('-', $new_dates[$i]);
  11. $new_dates[$i] = $GLOBALS['months'][abs($new_dates[$i][1])-1] . ' ' . abs($new_dates[$i][2]) . ', ' . $new_dates[$i][0];
  12. }
  13. $text = str_replace($dates, $new_dates, $text);
  14. return $text;
  15. }
  16. ?>

Report this snippet  

You need to login to post a comment.