Time conditional in PHP
Working on a WooCommerce project and there are products that are available daily until they sell out or until noon so they can be delivered. I use this function and pair it with the $product->is_in_stock() from the Woo WC_product class to provide conditional content in the template.
function wc_valid_time() {
// Straight PHP using DateTime class
// date_default_timezone_set('America/Chicago');
// $current_time = new DateTime();
// $current_time->setTimezone(new DateTimeZone('America/Chicago'));
// or, let WP do the lifting, as TimeZone is already set
$current_time = current_time("H:i");
$start_time = "00:01"; // 12:01 am
$cutoff_time = "12:00"; // 12:00 pm
$right_now = DateTime::createFromFormat('H:i', $current_time);
$time2 = DateTime::createFromFormat('H:i', $start_time);
$time3 = DateTime::createFromFormat('H:i', $cutoff_time);
if ($right_now > $time2 && $right_now < $time3):
return true;
else :
return false;
endif;
}
EDIT 6/3/16:
It became necessary to filter for day of week as well as time of day, so below is how I did that:
function wc_valid_day() {
// timezone is already set in WP control panel
// date_default_timezone_set('America/Chicago');
$current_day = current_time('D'); // day as three letter text
// $current_time = new DateTime();
// $current_time->setTimezone(new DateTimeZone('America/Chicago'));
$saturday = 'Sat';
$sunday = 'Sun';
$what_day = DateTime::createFromFormat('D', $current_day);
$date2 = DateTime::createFromFormat('D', $saturday);
$date3 = DateTime::createFromFormat('D', $sunday);
if ($what_day == $date2 || $what_day == $date3):
return false;
else :
return true;
endif;
}
Inside the loop on the template page for these products I use these two functions with the WooCommerce is_in_stock() function in a conditional to show the time/day appropriate markup.