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 todate(), 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 thestrtotime()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
strtotime($date)converts your input string2018-02-15into a Unix timestamp (a numeric representation of the date).strtotime('+1 month', $original_timestamp)takes that timestamp and adds one month to it, returning a new timestamp for2018-03-15.date('Y-m-d', $new_timestamp)formats the new timestamp back into theYYYY-MM-DDstring 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
相关产品推荐
相关产品推荐

