昨天工作正常,代码没有变化。
echo date("M", strtotime("-3 month", time()) );
echo date("M", strtotime("-2 month", time()) );
echo date("M", strtotime("-1 month", time()) );
echo date("M", time());
它昨天产生的输出正如你所料 - 即4月,5月,6月,7月
今天它与五月五月七月相呼应
有什么想法吗?
提前致谢。
答案 0 :(得分:13)
可能与错误#44073
有关你可以尝试这样的事情:
echo date("M", strtotime("-3 month", strtotime(date("F") . "1")) ) . "\n";
echo date("M", strtotime("-2 month", strtotime(date("F") . "1")) ) . "\n";
echo date("M", strtotime("-1 month", strtotime(date("F") . "1")) ) . "\n";
echo date("M", time()) . "\n";
(strtotime
的评论部分中提供的解决方案; direct link)
输出:
Apr
May
Jun
Jul
有种日期格式和月份名称的“作弊”以及所有......
答案 1 :(得分:8)
戈登正确地确定了这个问题,但我想提出另一个有用的解决方案,而不是技术方面。只需在你的strtotime中使用“第一天”或“最后一天”。例如,以下这些例子在一个月的31日克服了这个问题:
// Today is May 31st
//All the following return 2012-04-30
echo date('Y-m-d', strtotime("last day of -1 month"));
echo date('Y-m-d', strtotime("last day of last month"));
echo date_create("last day of -1 month")->format('Y-m-d');
// All the following return 2012-04-01
echo date('Y-m-d', strtotime("first day of -1 month"));
echo date('Y-m-d', strtotime("first day of last month"));
echo date_create("first day of -1 month")->format('Y-m-d');
答案 2 :(得分:4)
尝试使用此代替strtotime
:
mktime(0, (date("n") - 3 + 12) % 12, 1)
我们的想法是取当前月份数(date("n")
),减去你想要的月数(这里是-3
),然后加12,然后得到模数12。
答案 3 :(得分:3)
这是众所周知的预期行为。原因是月是没有固定长度的相对日期。来自http://www.gnu.org/software/tar/manual/html_node/Relative-items-in-date-strings.html#SEC120
时间位移的单位可以通过字符串“年”或“月”来选择,以便移动整年或数月。这些是模糊单位,因为年和月的持续时间并不相同。更精确的单位是'两周',值14天,'周'值7天,'天'值24小时,'小时'值60分钟,'分钟'或'分钟'值60秒,和'秒'或'秒'价值一秒钟。接受并忽略这些单位的's'后缀。
因此(强调我的)
单位模糊可能会导致相关项目出现问题。例如,'2003-07-31 -1 month'可能会评估为2003-07-01,因为2003-06-31是无效日期。 要更可靠地确定上个月,您可以询问当月15日之前的月份。例如:
$ date -R Thu, 31 Jul 2003 13:02:39 -0700 $ date --date='-1 month' +'Last month was %B?' Last month was July? $ date --date="$(date +%Y-%m-15) -1 month" +'Last month was %B!' Last month was June!
以上可以用PHP表示为
echo date('M', strtotime(date('Y-m-') . '15 -1 month'));
答案 4 :(得分:2)
从PHP 5.3(参考:https://bugs.php.net/bug.php?id=44073)及更高版本,你可以做到:
“first day of +1 month
”或“first day of next month
”或甚至“last day of next month
”
示例:
$date = '2015-12-31';
echo date("Y-m-d", strtotime($date ."first day of previous month"));
将产生:2015-11-01
这不会计算+30天时间内的天数。
答案 5 :(得分:0)
一种简单的方法就是像这样写
回音日期(“M”,strtotime(“今年+3个月”));
或
回音日期(“M”,strtotime(“本月-3个月”));
取决于你使用它...