开发者

strtotime returns incorrect timestamp for '-1 month'

I've using CCK date field. strtotime at end of Mart (>=29 Mar) will return incorrect result for strtotime('1- month').

// Current date Mar 30
$time = strtotime('-1 month');
print date('m/d开发者_运维技巧/Y', $time);

Any ideas ?


This is counter intuitive, but:

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

For the same reason:

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

There is no way I know of to get "same day last / next month" using the relative date/time formats of PHP.


My solution

/*
 * 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;
  }
}


I'm not that familiar with drupal but you could use something like:

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

to give you the day last month and if it exceeded the total number of days, ex Feb 30th it would go back down using the min function min (28).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜