假设我有一个变量$day
。它可以是Monday
到Sunday
之间的任何内容。我如何使用$day
变量并将其增加1 day
?
比方说,我有$day = "Friday"
。如何将其增加到Saturday
?
答案 0 :(得分:3)
使用date()和strtotime()在字符串中添加“+1天”:
<?php
$day = "friday";
$day = date('D',strtotime($day.'+1 day'));
echo $day; // "Saturday"
?>
答案 1 :(得分: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"));
答案 2 :(得分: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")
将返回当前日期的下一个星期一。干杯!
答案 3 :(得分:0)
你最好使用一个数组:
$your_integer = 10;
$weekdays = array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday');
print($weekdays[$your_integer % 7]);
通过递增$your_integer
,您将遍历$weekdays
- 数组;模运算(%
)使您保持在正确的范围内,因此10%7将产生3,因此输出将是星期四。
答案 4 :(得分:0)
重复使用可能有点简单:
$nextday = array(
"Monday" => "Tuesday",
"Tuesday" => "Wednesday",
"Wednesday" => "Thursday",
"Thursday" => "Friday",
"Friday" => "Saturday",
"Saturday" => "Sunday",
"Sunday" => "Monday",
);
$day = $nextday[$day];
答案 5 :(得分:0)
在数组中旋转模式的思考很好,但是如果你试图复制时间函数,不要这样做。 PHP有一个整洁的 strtotime(),可以创造奇迹。
$ts = strtotime( "+3 day", strtotime("December 30, 2007"));
echo date("r", $ts );
这会给你:
Wed, 02 Jan 2008 00:00:00 -0500
答案 6 :(得分:0)
使用数组会更好。但这也会奏效。
$day = "Friday";
$next_day = date('l', strtotime("{$day} +1 DAY"));
答案 7 :(得分:0)
$time = strtotime(<your_date_as_a_string>) + (60*60*12); // seconds in 12 hours
$date = strftime(<format_you want>, $time); // or date(<same params>)