我想在每个星期三上午12点更新我的日期。在PHP的下拉列表中

时间:2015-10-14 04:08:52

标签: php datetime

我想在每个星期三上午12点更新我的日期。在PHP的下拉列表中保持不变直到下周三。

以下是我的代码:

$now    = time(); // current timestamp
$today  = date("w", $now); // "w" returns the weekday (number)
$wednesday = 3; // 5th day of the week (sunday = 0)

if ($today == $wednesday) {
    $ts       = $now; // today is wednesday, don't change the timestamp
    $daysLeft = 0; // no days left!
} else {

    $daysLeft = $wednesday-$today; // get the left days
    $ts = $now + 84600 * $daysLeft; // now + seconds of one day * days left
}

?>

<h1>
    Forecast for <?php echo date("Y-m-d", $ts) ?>
</h1>

它在星期三的日期保持不变,这是正确的,然后在星期四开始后迅速改变。虽然我希望它能在下周三之前保持不变。

1 个答案:

答案 0 :(得分:1)

我认为你的问题太复杂了。

<?php
$today = time();
$nextWed = strtotime('next wednesday');

if(date('D', $today) === 'Wed') {
    $ts = date('Y-m-d', $today);
} else {
    $ts = date('Y-m-d', $nextWed);
}
echo '<h1>Forecast for '.$ts.'</h1>';
?>

发生了什么?

  1. 获取今天的时间戳
  2. 获取下周三的时间戳
  3. 如果今天是星期三,$ts =今天的日期
  4. 如果今天不是星期三,$ts =下周三的日期
  5. 回应您的结果
  6. 快乐的编码!

    修改

    <?php
    $now = time();
    $today = date('Y-m-d', $now);
    if(date('D', $now) === 'Wed') { $nextWed = strtotime($today); }
    if(date('D', $now) === 'Thu') { $nextWed = strtotime("$today - 1 days"); }
    if(date('D', $now) === 'Fri') { $nextWed = strtotime("$today - 2 days"); }
    if(date('D', $now) === 'Sat') { $nextWed = strtotime("$today - 3 days"); }
    if(date('D', $now) === 'Sun') { $nextWed = strtotime("$today - 4 days"); }
    if(date('D', $now) === 'Mon') { $nextWed = strtotime("$today - 5 days"); }
    if(date('D', $now) === 'Tue') { $nextWed = strtotime("$today - 6 days"); }
    $ts = date('Y-m-d', $nextWed);
    echo '<h1>Forecast for '.$ts.'</h1>'
    ?>