PHP:使用strtotime的奇怪输出

时间:2013-09-10 06:54:23

标签: php strtotime

我有这个代码,这在code.org上工作正常但在我的服务器上这只是回显1970-1-1

<?php
$str = 'Posted: Thu Sep 05, 2013 3:40 pm ';
$listdate = preg_replace('/Posted: /','',$str );
$listdate = date('Y-m-d',strtotime($listdate)); 
echo $listdate;

我尝试过设置date_default_timezone_set('UTC'),但这对我没用。

对这种奇怪的行为有什么想法吗?

注意:For PHP Info of my server

1 个答案:

答案 0 :(得分:0)

您是否在脚本之前设置了date_default_timezone_set?

正如php文档中所建议的那样:

  

为避免令人沮丧的困惑,我建议您随时致电   使用strtotime()之前的date_default_timezone_set('UTC')。

     

因为UNIX Epoch始终是UTC;你最有可能输出   如果你不这样做,那是错误的时间。

     

干杯

如果你这样做了,也许可以检查输出通常是另一个日期?

E.G:

$listdate = date("Y-m-d",strtotime("now"));

另外,mktime对您有用吗?

评论后编辑:

看起来你并不是唯一一个遇到PHP 5.3问题的人,实际上,总是来自文档,用户经历了类似的事情并为Windows平台提供了解决方案:

  

这里的大多数脚本都依赖于PHP识别正确的区域   当一个没有设置,但并不总是发生。

     

例如,PHP 5.3.3为检测到的'8.0 / no提供了'UTC'结果   DST”。没什么帮助。

     

因此,对于我们这些非常好的理由真的无法设定时间的人   .ini文件的脚本中的区域,这里是一个用于a的函数   Windows环境,将默认时区设置为OS时间   区域并返回检测到的和设置的文本。

<?php 
function date_system_timezone_set(){ 
  $shell = new COM("WScript.Shell") or die("Requires Windows Scripting Host"); 
  $time_bias = -($shell->RegRead( 
"HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control 
\\TimeZoneInformation\\Bias"))/60; 
  $ab = -($shell->RegRead( 
"HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control 
\\TimeZoneInformation\\ActiveTimeBias"))/60; 
  $sc = $shell->RegRead( 
"HKEY_USERS\\.DEFAULT\\Control Panel\\International\\sCountry"); 
  foreach(timezone_abbreviations_list() as $tza) foreach($tza as $entry){ 
    $country = strtok($entry['timezone_id'],'/'); 
    $locale = strtok('|'); 
    if($country==$sc && $ab==($entry['offset']/60/60) && ($ds = $time_bias!=$ab)==$entry['dst']){ 
      date_default_timezone_set($timezone_identifier = $country."/".$locale); 
      return sprintf('%.1f',$ab)."/".($ds?'':'no ').'DST'." ".$timezone_identifier; 
     } 
   } 
  return false; 
 } 
?>

此外,在maaaaaaaaaany搜索之后,我发现了许多人说在PHP 5+中你必须在PHP.ini中定义date.timezone!

来自论坛:

  必须在PHP 5.3.0 +

中设置php.ini中的

date.timezone选项

链接到topi:http://www.silverstripe.org/installing-silverstripe/show/15398?start=8

所以,请尝试添加到PHP.ini date.timezone!

其他更新(总是在更多评论之后):

由于您的代码在解析日期时有效,请使用日期解析器或尝试:

<?php
$str = 'Posted: Thu Sep 05 2013 3:40 pm ';
$listdate = preg_replace('/Posted: /','',$str );
$listdate = date('Y-m-d',strtotime($listdate)); 
echo $listdate;
?>

这回事给我2013-09-05

如果这仍然无效,请按建议datetime or date parsers ...

使用here

最后和最终修改:

使用php 5在我的crunchbang linux上尝试了这个代码,它确实有效:

<?php
$str = 'Posted: Thu Sep 05, 2013 3:40 pm ';
$listdate = preg_replace('/Posted: /','',$str );
$date = date_create_from_format('D M j, Y g:i a ', $listdate);
echo date_format($date, 'Y-m-d');
?>
相关问题