I need to convert any date to a date within 1 month from today. Dates that are smaller than today should be converted to next month.
For example, current day is 2018-09-11 and dates are:
$dates = ['2018-08-01', '2018-09-11', '2018-09-15', '2018-10-15', '2018-12-31', '2019-01-01', '2019-01-31'];
Results should be as follows, respectively:
$result = ['2018-10-01', '2018-09-11', '2018-09-15', '2018-09-15', '2018-09-30', '2018-10-01, '2018-09-30'];
Edit: I have tried so far using strtotime('+1 month') but it fails on dates such as 2018-10-31 since it'll give 2018-12-01. It also fails on using strtotime('-1 month') on dates such as 2018-10-31 where it gives 2018-10-01 instead of 2018-09-30.
My current solution is following, but I believe it can be done MUCH simpler somehow:
$timestamp = strtotime('2018-10-31');
if (date('d', $timestamp) > date('t')) {
$date = date('Y-m-t');
} elseif(date('d', $timestamp) < date('d')) {
$year = date('Y');
$month = date('m') == 12 ? 1 : (intval(date('n')) + 1);
if ($month < 10) {
$month = '0'.$month;
}
$day = date('d', $timestamp);
$date = $year . '-' . $month . '-' . $day;
} else {
$date = date('Y-m') . '-' . date('d', $timestamp);
}
You can use
if('2018-09-11'<date("Y-m-d"))
date("Y-m-d", strtotime("+1 month", '2018-09-11'));
for example
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.