2017-01-19 143 views
0

我想爲我的功能工作做一個條件。這是邏輯。PHP條件日期處理 - 比較時間和日期

預訂截止日期是今天中午12點。 如果當前時間在關閉時間之前(比如今天上午11點),則運行函數x。我需要在預訂關閉時設定時間,並將其與當前時間進行比較。

$tz_object = new DateTimeZone('Africa/Kampala'); 
$datetime = new DateTime(); 
$datetime->setTimezone($tz_object); 
$timeNow = $datetime->format('Y\-m\-d\ h:i:s'); 

$date = new DateTime(); 
$date->setTime(23,00); 
$timeAllowed = $datetime->format('Y\-m\-d\ h:i:s'); 

if ($timeNow < $timeAllowed) { 
    function woo_add_cart_fee() { 

     global $woocommerce; 

     $woocommerce->cart->add_fee(__('Custom', 'woocommerce'), number_format(5)); 

    } 
    add_action('woocommerce_cart_calculate_fees', 'woo_add_cart_fee'); 
} 

回答

1

比較datetime對象是容易的。您不需要將日期時間轉換爲字符串。

// time when booking closes 
$bookclose = new \DateTime(); 
$bookclose->setTimezone(new DateTimeZone('Africa/Kampala')); 
$bookclose->setTime(12,0,0); 

// fake a time that the booking is being made for testing 
$bookingtime = new \DateTime(); 
$bookingtime->setTimezone(new DateTimeZone('Africa/Kampala')); 

$bookingtime->setTime(11,59,59); 
echo 'Booking time is ' . $bookingtime->format('d/m/Y H:i:s'); 
if ($bookingtime < $bookclose) { 
    echo ' ALLOWED'.PHP_EOL; 
} else { 
    echo ' NOT ALLOWED'.PHP_EOL; 
} 

$bookingtime->setTime(12,0,0); 
echo 'Booking time is ' . $bookingtime->format('d/m/Y H:i:s'); 
if ($bookingtime < $bookclose) { 
    echo ' ALLOWED'.PHP_EOL; 
} else { 
    echo ' NOT ALLOWED'.PHP_EOL; 
} 

$bookingtime->setTime(12,0,1); 
echo 'Booking time is ' . $bookingtime->format('d/m/Y H:i:s'); 
if ($bookingtime < $bookclose) { 
    echo ' ALLOWED'.PHP_EOL; 
} else { 
    echo ' NOT ALLOWED'.PHP_EOL; 
} 

結果:

Booking time is 19/01/2017 11:59:59 ALLOWED 
Booking time is 19/01/2017 12:00:00 NOT ALLOWED 
Booking time is 19/01/2017 12:00:01 NOT ALLOWED