2017-05-29 60 views
1

我認爲這將是一個輕而易舉的事情,但我發現它比我想象的更難。我如何知道今天是在PHP中的聖誕節和主顯節之間?

我每天都要檢查今天是否在聖誕節(12月25日)和主顯節(1月6日)即聖誕節之間。

我遇到的問題是隨着年份的變化,在那段時期的中期變化。

我基本的if語句應該是:

$this_year_today = date("d-M-Y"); 
$christmas = date('d-M-Y', strtotime("25 December ".$year)); 
$epiphany = date('d-M-Y', strtotime("6 January ".$year)); 

if(($this_year_today >= $christmas) && ($this_year_today < $epiphany)){ 
     $season= "Christmastide";} 

但如果今天是聖誕節後的2017年則頓悟日期是2018年,但如果今天是頓悟之前那麼聖誕節是2016年做我的頭有點。最簡單的方法是做什麼。我試着用的strtotime說「去年聖誕節」,但沒有似乎工作...

THX

+2

怎麼樣不使用年?如果你不使用年份,你可以比較日期並說'christmasdate SacrumDeus

+0

@SacrumDeus''12 -26'<'12 -31'&& '12 -31'<'1-6'' ...?這永遠不會是真的...... – deceze

+1

你的日期應該是'1226'和'1231'。有了這個,你可以很容易地比較,因爲1231大於1226,'0106'小於'1231'。也許它會有所幫助 – SacrumDeus

回答

1
function isChristmastide() { 
    $month = date('n'); 
    $day = date('j'); 
    return ($month == 12 && $day >= 25) || ($month == 1 && $day <= 6); 
} 

echo isChristmastide() ? 'Ho ho ho' : 'No no no'; 

其他替代:

$today = date('nj'); 
return 1225 <= $today || $today <= 16; 

雖然我找到了可讀性懷疑。

0

未經測試,但也許你可以嘗試像這樣使用數字值的時間,而不是一個日期嗎?

$year=date('Y'); 
$nextyear=$year+1; 

$now=time(); 
$christmas = strtotime("25 December $year"); 
$epiphany = strtotime("6 January $nextyear"); 

$season=($now >= $christmas && $now <= $epiphany) ? 'Christmastide' : 'Not Christmastide'; 

echo $season; 
+0

如果第三個1月你想檢查去年的聖誕節 –

+0

如果第三個1月你會檢查今年的頓悟... –

+1

你可以考慮前一年如果當前月份是一月份,如果當前月份是十二月,則是當前年份。有了這個結果,你檢查日期是否大於12月25日,或分別小於6月 – frankiehf

0

感謝frankiehf,現在應該是答案:

$month = date('M'); 
$year = date('Y'); 
$last_year = $year-1; 
$next_year = $year+1; 

if($month == "Jan"){ 
    $christmas = date('d-M-Y', strtotime("25 December ".$last_year)); 
    $epiphany = date('d-M-Y', strtotime("6 January ".$year));} 
else{ 
    $christmas = date('d-M-Y', strtotime("25 December ".$year)); 
    $epiphany = date('d-M-Y', strtotime("6 January ".$next_year));} 

if(($this_year_today >= $christmas) && ($this_year_today < $epiphany)){ 
     $season= "Christmastide";} 
+0

這是相當複雜。 – deceze

1

試試這個,沒必要弄混淆的一年。

$current_day = date('j'); //get Day of the month without leading zeros 
$current_month = date('n'); //get Numeric representation of a month, without leading zeros 
$season = ''; 
switch($current_month): 
    case 1: 
     $season = $current_day<=6 ? 'Christmastide' : 'Not Christmastide';    
     break; 
    case 12: 
     $season = $current_day>=25 ? 'Christmastide' : 'Not Christmastide'; 
     break; 
    default: 
     $season = 'Not Christmastide'; 
     break; 
endswitch; 
echo $season; 

Demo

相關問題