3

假设我有一个变量$day。它可以是从Monday到 的任何东西Sunday。我如何使用该$day变量并将其递增1 day

比方说,我有$day = "Friday". 如何将其增加到 a Saturday

4

8 回答 8

3

使用date()strtotime()将 '+1 day' 添加到您的字符串中:

<?php
$day = "friday";
$day = date('D',strtotime($day.'+1 day'));
echo $day; // "Saturday"
?>
于 2012-11-09T02:15:43.893 回答
1

使用数组。在不久的将来,工作日几乎不可能改变(讽刺)

// $weekday can be a string or a numeric value (1=Monday, 0,7=Sunday)
function getNextDayOfWeek($weekday, $count = 1) {
    static $weekdays = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');

    if (!is_numeric($weekday)) {
        $weekday = (int) array_search(ucfirst(strtolower($weekday)), $weekdays);
    }
    // make $count positive!
    if ($count < 0) $count = ($count % -7) + 7;

    return $weekdays[($weekday + $count) % 7];
}

如果您担心本地化,请使用翻译数组:)

$weekdays_fr = array('Monday' => 'lundi', 'Tuesday' => 'mardi', ...);

$nextDay_fr = $weekdays_fr[getNextDayOfWeek('Friday')];  //= 'samedi'

**编辑**

这是使用内置 PHP 函数的另一种方法,但我仍然更喜欢数组解决方案。

$weekday = 'Friday';

$nextDay = strftime('%A', strtotime("{$weekday} +1 day"));
于 2012-11-09T02:08:58.400 回答
1

这是一个相当干净的解决方案,不使用数组:

$day = "Monday"
$NextDay = strtotime("+1 day", strtotime($day));
echo date("l", $NextDay);

综合解决方案:

$day = "Monday";
echo date("l", strtotime("+1 day", strtotime($day)));

请记住,strtotime("Monday")将从当前日期的下周一返回。干杯!

于 2012-11-09T02:21:23.397 回答
0

你最好使用一个数组:

$your_integer = 10;
$weekdays = array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday');
print($weekdays[$your_integer % 7]);

通过递增$your_integer,您将循环遍历$weekdays-array; 模运算 ( %) 使您保持在正确的范围内,因此 10 % 7 将产生 3,因此输出将是星期四。

于 2012-11-09T02:11:11.480 回答
0

重复使用可能更简单一些:

$nextday = array(
    "Monday" => "Tuesday",
    "Tuesday" => "Wednesday",
    "Wednesday" => "Thursday",
    "Thursday" => "Friday",
    "Friday" => "Saturday",
    "Saturday" => "Sunday",
    "Sunday" => "Monday",
);

$day = $nextday[$day];
于 2012-11-09T02:13:14.350 回答
0

对数组中的旋转模式进行很好的思考,但以防万一你试图复制时间函数,不要这样做。PHP 有一个简洁的strtotime()可以创造奇迹。

$ts = strtotime( "+3 day", strtotime("December 30, 2007"));
echo date("r", $ts );

这给了你:

Wed, 02 Jan 2008 00:00:00 -0500

于 2012-11-09T02:13:32.560 回答
0

使用数组会更好。但这也可以。

$day = "Friday";
$next_day = date('l', strtotime("{$day} +1 DAY"));
于 2012-11-09T02:14:27.110 回答
0

参见strtotime()strftime()

$time = strtotime(<your_date_as_a_string>) + (60*60*12); // seconds in 12 hours
$date = strftime(<format_you want>, $time); // or date(<same params>)
于 2012-11-09T17:38:48.163 回答