PHP Date range formatter


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

Takes one or two PHP timestamps, and returns a somewhat humanized string representing the date range

* Jun 7th, 2013
* Jun 7th-11th, 2013
* Jun 7th-Jul 3rd, 2013
* Jun 7th, 2013-Jan 1st, 2013


Copy this code and paste it in your HTML
  1. /**
  2.  * Takes one or two TIMESTAMPs, and an optional formatting array of the form ($year, $month, $day),
  3.  * and returns a date that is appropriate to the situation
  4.  * @param int $start
  5.  * @param int $end
  6.  * @param array $fmt
  7.  * @return boolean|string
  8.  */
  9. function _pj_pretty_date( $start, $end = NULL, $fmt = NULL ) {
  10. if( ! isset( $start ) ) {
  11. return false;
  12. }
  13.  
  14. if( ! isset( $fmt ) ) {
  15. // default formatting
  16. $fmt = array( 'Y', 'M', 'j' );
  17. }
  18. list( $yr, $mon, $day ) = $fmt;
  19.  
  20. if( ! isset( $end) || $start == $end ) {
  21. return( date( "$mon $day, $yr", $start ) );
  22. }
  23. if( date( 'M-j-Y', $start ) == date( 'M-j-Y', $end ) ) {
  24. // close enough
  25. return date( "$mon $day, $yr", $start );
  26. }
  27.  
  28.  
  29. // ok, so $end != $start
  30.  
  31. // let's look at the YMD individually, and make a pretty string
  32. $dates = array(
  33. 's_year' => date( $yr, $start ),
  34. 'e_year' => date( $yr, $end ),
  35.  
  36. 's_month' => date( $mon, $start ),
  37. 'e_month' => date( $mon, $end ),
  38.  
  39. 's_day' => date( $day, $start ),
  40. 'e_day' => date( $day, $end ),
  41.  
  42. );
  43. // init dates
  44. $start_date = '';
  45. $end_date = '';
  46.  
  47. $start_date .= $dates['s_month'];
  48. if( $dates['s_month'] != $dates['e_month'] ) {
  49. $end_date .= $dates['e_month'];
  50. }
  51.  
  52. $start_date .= ' '. $dates['s_day'];
  53. if( $dates['s_day'] != $dates['e_day'] || $dates['s_month'] != $dates['e_month'] ) {
  54. $end_date .= ' ' . $dates['e_day'];
  55. }
  56.  
  57. if( $dates['s_year'] != $dates['e_year'] ) {
  58. $start_date .= ', ' . $dates['s_year'];
  59. if( $dates['s_month'] == $dates['e_month'] ) {
  60. if( $dates['s_day'] == $dates['e_day'] ) {
  61. // same day, same month, different year
  62. $end_date = ' ' . $dates['e_day'] . $end_date;
  63. }
  64. // same month, but a different year
  65.  
  66. $end_date = $dates['e_month'] . $end_date;
  67. }
  68. }
  69. $end_date .= ', ' . $dates['e_year'];
  70.  
  71. $complete_date = trim( $start_date ) . '–' . trim( $end_date );
  72.  
  73. return $complete_date;
  74. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.