【问题标题】:php date format converting problemphp日期格式转换问题
【发布时间】:2011-11-05 06:58:15
【问题描述】:

这是我尝试将日期转换为不同格式的函数。

/*  example:
*   dateString          =   '03/25/2010';
*   inputDateFormat     =   '%m/%d/%Y';
*   ouputDateFormat     =   'Y-m-d';
*   return              ->  '2010-03-25';
*/  
function formatDate($dateString,$inputFormat=NULL,$outputFormat=NULL){
    if($dateString==''||$dateString==NULL) return '';
    $t =  strptime($dateString,$inputFormat);
    return gmdate($outputFormat,mktime($t[tm_sec],$t[tm_min],$t[tm_hour],($t[tm_mon]+1),($t[tm_mday]+1),($t[tm_year]+1900)));
}

我的问题是

当我尝试使用以下行将此日期 Wed, 19 Jan 2011 21:16:37 +0000 转换为 2011-01-19 21:16:37 时:

echo formatDate('Wed, 19 Jan 2011 21:16:37 +0000','%a, %d %b %Y %H:%M:%S','Y-m-d H:i:s');

结果是这样的:

2011-01-21 11:16:21

为什么我要多出 2 天的日期。 你有什么想法吗?

【问题讨论】:

    标签: php date format


    【解决方案1】:

    改用这个:

      function formatDate($dateString, $outputFormat=NULL){
          return date($outputFormat, strtotime($dateString));
      }
    
      echo formatDate('Wed, 19 Jan 2011 21:16:37 +0000','Y-m-d H:i:s');
    

    【讨论】:

    • 它有效,谢谢 :) 但我需要指定输入格式,你对此有何建议?
    • 没问题,提醒一下,如果您的日期无效,您应该添加验证。在 php 5.1 strtotime 之前返回 -1,之后返回 FALSE。
    • 当我给出这样的日期 03/02/2011 时,它无法理解哪一天是一天,哪一天是月份:)
    • 您甚至可以在调用 formatDate 时输入:'now'、'tomorrow' 或 'now + 2 days'
    【解决方案2】:

    这是一个疯狂的猜测,但也许您需要设置 yoru 时区?

    date_default_timezone_set()(需要 PHP 5)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多