【问题标题】:Given a time, how can I find the time one month ago给定时间,我怎样才能找到一个月前的时间
【发布时间】:2010-12-31 00:23:12
【问题描述】:

给定一个时间,我怎样才能找到一个月前的时间。

【问题讨论】:

  • “一个月”是指到第二个的 30 天吗?或者您想针对 28 天或 29 天的 2 月问题进行调整?
  • 你能再具体一点吗?例如,如果现在是 12 月 29 日下午 2:00,那么一个月前的时间不是 11 月 29 日下午 2:00 吗?

标签: php date time


【解决方案1】:
strtotime( '-1 month', $timestamp );

http://php.net/manual/en/function.strtotime.php

【讨论】:

【解决方案2】:

在 php 中你可以使用 strtotime("-1 月")。在此处查看文档:http://ca3.php.net/strtotime

【讨论】:

    【解决方案3】:

    我们可以通过使用 PHP 的现代日期处理来实现相同的目的。这需要 PHP 5.2 或更高版本。

    // say its "2015-11-17 03:27:22"
    $dtTm = new DateTime('-1 MONTH', new DateTimeZone('America/Los_Angeles')); // first argument uses strtotime parsing
    echo $dtTm->format('Y-m-d H:i:s'); // "2015-10-17 03:27:22"
    

    希望这可以为这个问题添加更多信息。

    【讨论】:

      【解决方案4】:
      <?php
      
      $date = new DateTime("18-July-2008 16:30:30");
      echo $date->format("d-m-Y H:i:s").'<br />';
      
      date_sub($date, new DateInterval("P1M"));
      echo '<br />'.$date->format("d-m-Y").' : 1 Month';
      
      ?> 
      

      【讨论】:

        【解决方案5】:

        PHP 5.2=

        $date = new DateTime(); // Return Datetime object for current time
        $date->modify('-1 month'); // Modify to deduct a month (Also can use '+1 day', '-2 day', ..etc)
        echo $date->format('Y-m-d'); // To set the format 
        

        参考:http://php.net/manual/en/datetime.modify.php

        【讨论】:

          【解决方案6】:

          此代码用于获取 1 个月前而不是 30 天

          $date = "2016-03-31";
          
          $days = date("t", strtotime($date));
          
          echo  date("Y-m-d", strtotime( "-$days days", strtotime($date) ));
          

          【讨论】:

            【解决方案7】:

            这些答案把我逼疯了。如果不跳过短短的几个月,您就无法减去 31 天并获得理智的结果。 我假设您只关心月份,而不是月份中的哪一天,例如按年份和月份过滤/分组事物。

            我会这样做:

            $current_ym = date('ym',strtotime("-15 days",$ts));

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2023-02-05
              • 2015-09-10
              • 2016-02-13
              • 1970-01-01
              • 1970-01-01
              • 2022-08-02
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多