PHP,如果基于当前系统日期


PHP if based on current system date

尝试设置一个根据用户日期/时间自动更新的页面。

需要运行2周的促销活动,每天都需要更改显示的图像。正在通读http://www.thetricky.net/php/Compare%20dates%20with%20PHP以便更好地处理php的时间和日期函数。测试起来有点棘手,但我基本上陷入了困境:

<?php
$dateA = '2012-07-16'; 
$dateB = '2012-07-17'; 
if(date() = $dateA){ 
  echo 'todays message';
}
else if(date() = $dateB){
    echo 'tomorrows message';
}
?>

我知道上面的功能设置是错误的,但我认为它解释了我的目标。时间无关紧要,它需要在午夜切换,这样日期无论如何都会改变。

您似乎需要这个:

<?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';
}
?>

您想要

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

我会后退一步,通过文件名处理它。类似于:

<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">

如果要进行日期计算,我建议使用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-16开始,则显示以下内容,因为现在是促销活动的第二天:

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