Recently I had this scenario where the client wanted the whole date range to be displayed instead of just the first and last date. So instead of June 6 - June 10 then wanted it to be displayed as June 6, 7, 8, 9, 10. Seems to be simple at first right? What if the range is July 30 - August 1? Then it has to be July 30, 31, August 1. What if it is December 31 to January 2. Then it has to be December 31, 2012 January 1, 2,
So I wrote this nifty function which does the job.
So if the inputs are
$date1 = 2011-07-28T04:00:00
$date2 = 2011-08-02T04:00:00
$output = "July 28, 29, 30, 31 August 01, 02"
So I wrote this nifty function which does the job.
function get_date_range($date1, $date2){ $start = date( 'Y-m-d', strtotime($date1) ); $end = date( 'Y-m-d', strtotime($date2) ); $current = $start; $range_string = ''; while( (strtotime($end)-strtotime($current)) >= 0 ){ $current_month = date( 'F', strtotime($current)); $current_year = date( 'Y', strtotime($current)); if($range_string && $current_year != $previous_year){ $range_string .= $current_year . ' '; } if($current_month != $previous_month){ $range_string .= $current_month . ' '; } $range_string .= date( 'd', strtotime($current)); if($current != $end){ $range_string .= ', '; } $previous_month = $current_month; $previous_year = $current_year; $current = date( 'Y-m-d', strtotime($current) + 86400); } return $range_string; }
So if the inputs are
$date1 = 2011-07-28T04:00:00
$date2 = 2011-08-02T04:00:00
$output = "July 28, 29, 30, 31 August 01, 02"
No comments:
Post a Comment