【问题标题】:strtotime returns incorrect timestamp for '-1 month'strtotime 为“-1 个月”返回不正确的时间戳
【发布时间】:2011-03-29 22:44:21
【问题描述】:

我使用的是 CCK 日期字段。 Mart 结束时的 strtotime (>=29 Mar) 将为 strtotime('1-month') 返回不正确的结果。

// Current date Mar 30
$time = strtotime('-1 month');
print date('m/d/Y', $time);

有什么想法吗?

【问题讨论】:

  • 这不是 Drupal 问题,它与所有 PHP 相关。
  • 虽然使用 date() 函数不是 Drupal 特有的,但重要的是要注意,对于 Drupal 中的大多数用途,应该使用 format_date() 函数 (api.drupal.org/api/drupal/includes--common.inc/function/…) 以便考虑了时区和其他 Drupal 特定的配置。

标签: php date


【解决方案1】:

这是违反直觉的,但是:

03/30/2011 - 1 month = 02/30/2011 => 03/02/2011

出于同样的原因:

03/31/2011 + 1 month = 04/31/2011 => 05/01/2011

我不知道使用relative date/time formats of PHP 来获得“上/下个月的同一天”。

【讨论】:

  • 但“上个月”也返回不正确的结果。无法在 CCK 日期字段中设置默认值;(谷歌也沉默了
【解决方案2】:

我的解决方案

/*
 * Implementation of hook_form_alter().
 */
function report_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case AUTO_REPORT_NODE_FORM:
      // Fix bug with strtotime('-1 month')
      $currentYear  = date('Y');
      $currentMonth = date('n');
      if($currentMonth == 1){
        $relevantMonth = 12;
        $relevantYear = $currentYear -1;
      }
      else{
        $relevantMonth = $currentMonth - 1;
        $relevantYear = $currentYear;
      }
      $form['field_datestamp'][0]['#default_value']['value'] = date("Y-m-d h:m:s", strtotime($relevantYear .'-'. $relevantMonth));
      break;
  }
}

【讨论】:

    【解决方案3】:

    我对drupal不太熟悉,但你可以使用类似的东西:

    min(date('t'), date('d')); // would yield 28 on March 30th
    

    为您提供上个月的日期,如果超过总天数,例如 2 月 30 日,它将使用 min 函数 min (28) 返回。

    【讨论】:

      猜你喜欢
      • 2012-04-15
      • 1970-01-01
      • 2012-02-23
      • 1970-01-01
      • 1970-01-01
      • 2013-01-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多