Skip to content

Instantly share code, notes, and snippets.

@timkinnane
Created April 7, 2013 23:37
Show Gist options
  • Save timkinnane/5333114 to your computer and use it in GitHub Desktop.
Save timkinnane/5333114 to your computer and use it in GitHub Desktop.
Generate date range regex, PHP.
function get_daterange_regex( $from, $to, $input_format ) {
// get the difference in months
$date1 = DateTime::createFromFormat( $from, $input_format );
$date2 = DateTime::createFromFormat( $to, $input_format );
$interval = $date1->diff($date2);
$months = $interval->m;
// get an array of the interveening months
$all_months = array();
for ($i = 0; $i<=$months; $i ++) {
$all_months[$i] = $date1->modify('+1 month');
}
$month_codes = array_map( 'acf_date_format', $all_months);
// return the regex string created from the array
return "/" . implode( "|", $month_codes ) . "/";
}
function acf_date_format($date) {
return date_format($date, 'Ym');
}
// e.g Get the regex string for finding posts between Dec 2011 and Mar 2012
$date_regex = get_daterange_regex( '2011-12', '2012-03', 'Y-m' );
// Outputs "/201112|201201|201202|201203/" depending on date formats given
echo $date_regex
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment