【问题标题】:Convert date to current month date将日期转换为当前月份日期
【发布时间】:2018-09-11 16:00:54
【问题描述】:

我需要将任何日期转换为从今天起 1 个月内的日期。小于今天的日期应转换为下个月。

例如,当天是 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'];

结果应分别如下:

$result = ['2018-10-01', '2018-09-11', '2018-09-15', '2018-09-15', '2018-09-30', '2018-10-01, '2018-09-30'];

编辑:到目前为止,我已经尝试过使用 strtotime('+1 month') 但它在 2018-10-31 等日期失败,因为它会给出 2018-12-01。它也无法在诸如 2018-10-31 之类的日期使用 strtotime('-1 month') ,它给出的是 2018-10-01 而不是 2018-09-30。

我目前的解决方案如下,但我相信它可以以某种方式更简单:

$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);
}

【问题讨论】:

  • 你能展示一下你到目前为止所做的尝试吗?
  • 如果您遇到特定的编程问题,我们很乐意为您提供帮助,但我们不是来为您编写代码或设计系统的。您至少需要尝试解决您自己的问题。请参阅How to Ask 一个好问题和What topics can I ask about here?doing more research 之后如果您有问题,您可以发布您尝试过的内容,并清楚地解释什么不起作用并提供Minimal, Complete, and Verifiable example
  • @RamRaider 我刚刚做了。
  • 您的结果数组有缺陷,9 月是 30 天,您的结果中有 2018-09-31
  • 不,没有更简单的方法,您可以使用 DateTime 对象等。但逻辑不会有太大差异。在不知道您是本月的最后一天的情况下,没有相对的方法可以获取本月的最后一天。

标签: php date


【解决方案1】:

你可以使用

if('2018-09-11'<date("Y-m-d"))
date("Y-m-d", strtotime("+1 month", '2018-09-11'));

例如

【讨论】:

  • 这不会检查日期是否为过去、月份中的天数或闰年。
  • 已更新。您可以用变量替换“2018-09-11”
  • @RinsadAhmed 使用 date('Y-m-d', strtotime("+1 month", '2018-10-31')) 将为您提供日期 2018-12-01。这就是为什么我不能真正使用 +- 1 个月
  • @Viktor 请问你是什么意思?
  • @RinsadAhmed 我希望从 2018 年 10 月 31 日开始得到 2018 年 11 月 30 日(本月的最后一天)而不是 2018 年 12 月 1 日。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-24
  • 1970-01-01
  • 1970-01-01
  • 2015-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多