2012-07-17 85 views
0

嘗試設置基於用戶日期/時間自動更新的頁面。PHP根據當前系統日期

需要運行一個促銷2周,每天需要更改顯示的圖像。 正在讀通過http://www.thetricky.net/php/Compare%20dates%20with%20PHP來得到關於PHP的時間和日期functions.Somewhat棘手的測試更好地處理,但我基本上就死在:

<?php 
$dateA = '2012-07-16'; 
$dateB = '2012-07-17'; 

if(date() = $dateA){ 
    echo 'todays message'; 
} 
else if(date() = $dateB){ 
    echo 'tomorrows message'; 
} 
?> 

我知道上面的函數是錯誤的,因爲它的設置,但我認爲它解釋了我的目標。 時間無關緊要,它需要在午夜切換,所以日期會改變。

+0

'if'需要'=='或''===。你正在使用一個'='。它是否編譯? – Lion 2012-07-17 13:50:57

回答

2

你似乎需要這樣的:

<?php 
$dateA = '2012-07-16'; 
$dateB = '2012-07-17'; 

if(date('Y-m-d') == $dateA){ 
    echo 'todays message'; 
} else if(date('Y-m-d') == $dateB){ 
    echo 'tomorrows message'; 
} 
?> 
+0

+1,雖然你可能需要調用:'date('Y-m-d')'而不是 – 2012-07-17 13:49:52

+0

你是對的,修正了 – 2012-07-17 13:50:48

+0

$ today = date('Y-m-d');如果($今天=== $ dateA){}否則10天后你有PHP計算日期()10次;)編輯,DOH,bigkm說同樣,對不起... – Cups 2012-07-17 14:14:53

0

我會去一步,通過文件名的處理。喜歡的東西:

<img src=/path/to/your/images/img-YYYY-MM-DD.jpg alt="alternative text"> 

所以,你的腳本會是這個樣子:

<img src=/path/to/your/images/img-<?php echo date('Y-m-d', time()); ?>.jpg alt="alternative text"> 
+1

這是什麼? – lusketeer 2012-07-17 13:50:34

+0

這是在特定日期顯示圖像的一種方法。 – PascalPrecht 2012-07-17 13:51:44

2

你想

<?php 
$today = date('Y-m-d') 
if($today == $dateA) { 
    echo 'todays message'; 
} else if($today == $dateB) { 
    echo 'tomorrows message'; 
} 
?> 
+0

謝謝,這應該是訣竅。 – RemeJuan 2012-07-17 14:48:58

0

如果你要做的日期計算,我推薦使用PHP的DateTime類別:

$promotion_starts = "2012-07-16"; // When the promotion starts 

// An array of images that you want to display, 0 = the first day, 1 = the second day 
$images = array( 
    0 => 'img_1_start.png', 
    1 => 'the_second_image.jpg' 
); 

$tz = new DateTimeZone('America/New_York'); 

// The current date, without any time values 
$now = new DateTime("now", $tz); 
$now->setTime(0, 0, 0); 

$start = new DateTime($promotion_starts, $tz); 
$interval = new DateInterval('P1D'); // 1 day interval 
$period = new DatePeriod($start, $interval, 14); // 2 weeks 

foreach($period as $i => $date) { 
    if($date->diff($now)->format("%d") == 0) { 
     echo "Today I should display a message for " . $date->format('Y-m-d') . " ($i)\n"; 
     echo "I would have displayed: " . $images[$i] . "\n"; // echo <img> tag 
     break; 
    } 
} 

鑑於推廣上07-16this displays下面開始,因爲它現在是促銷的第二天:

Today I should display a message for 2012-07-17 (1) 
I would have displayed: the_second_image.jpg 
相關問題