简体   繁体   English

将日期转换为当前月份的日期

[英]Convert date to current month date

I need to convert any date to a date within 1 month from today. 我需要将任何日期转换为从今天起1个月内的日期。 Dates that are smaller than today should be converted to next month. 日期小于今天的日期应转换为下个月。

For example, current day is 2018-09-11 and dates are: 例如,当前日期为2018-09-11,日期为:

$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. 编辑:到目前为止,我已经尝试过使用strtotime('+ 1 month'),但是它在诸如2018-10-31之类的日期上失败了,因为它将给出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. 它也无法在诸如2018-10-31之类的日期上使用strtotime('-1 month')给出2018-10-01而不是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 例如

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM