You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP中如何显示下个月日期?现有代码无法得到预期结果求助

Fixing the Next Month Date Calculation in PHP

Let's break down what's wrong with your code and how to fix it to get the desired output of 2018-03-15.

Issues in the Original Code

  • Incorrect format string in date(): You passed '$date' as the first argument to date(), but this function expects a format specifier (like 'Y-m-d') to define how the date should be formatted.
  • Syntax error: Missing closing parenthesis ) for the strtotime() call.
  • Relative date reference: strtotime('+1 month') adds a month to the current date by default, not your specified $date. You need to base the calculation on your input date.

Corrected Code

Here's the fixed version that will output 2018-03-15:

$date = "2018-02-15";
// Convert the original date to a timestamp, then add 1 month
$next_month_timestamp = strtotime('+1 month', strtotime($date));
// Format the timestamp to the desired 'Y-m-d' format
$next_month = date('Y-m-d', $next_month_timestamp);
echo $next_month; // Outputs: 2018-03-15

Simplified Version

You can also combine the steps into a single line if you prefer:

$date = "2018-02-15";
$next_month = date('Y-m-d', strtotime('+1 month', strtotime($date)));
echo $next_month;

How It Works

  1. strtotime($date) converts your input string 2018-02-15 into a Unix timestamp (a numeric representation of the date).
  2. strtotime('+1 month', $original_timestamp) takes that timestamp and adds one month to it, returning a new timestamp for 2018-03-15.
  3. date('Y-m-d', $new_timestamp) formats the new timestamp back into the YYYY-MM-DD string format you need.

Edge Case Consideration

Note that if your input date is the last day of a month (e.g., 2020-02-29), strtotime('+1 month') will handle it intelligently (returning 2020-03-29 instead of an invalid date). If you want to always get the last day of the next month, you could use strtotime('last day of next month', strtotime($date)) instead.

内容的提问来源于stack exchange,提问作者Richard Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:39:34