2015-04-01 138 views
0

我有一个非常奇怪的错误,我不明白。出于某种原因,某些日期未被正确解析。解析日期错误

代码:

$day = strtotime($_GET['d']."-".$_GET['m']."-".$_GET['y']); 
$dateTimeZone = new DateTimeZone("Europe/Prague"); 
$dateTime = new DateTime($day, $dateTimeZone); 
$offset = ($dateTimeZone->getOffset($dateTime))/3600; 

现在真正奇怪的是.... 如果我通过在特定的数字,它的工作原理,但它与其他人犯规...

例如一个像这样的URL将工作:

d=15&m=12&y=2014 

但这:

d=12&m=12&y=2014 

显示

Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct(): Failed to parse time string (1418252400) at position 7 (4): Unexpected character' in

我试图用它进行试验,也改变了的strtotime的格式,但没有运气,它只是似乎完全是随机的工作....

+0

你为什么在不同的参数发送日期? – 2015-04-01 16:20:05

+0

你不需要使用strtotime,你可以直接将日期字符串传递给'DateTime'对象。错误可能是由于日,月和年的顺序不正确。它应该是YYYY-MM-DD。 – 2015-04-01 16:20:05

+0

当发生这种情况时'var_dump($ day)'会显示什么? – Barmar 2015-04-01 16:20:13

回答

3

当发送时间戳DateTime对象的参数,你必须使用@符号作为前缀。请参阅本手册(UNIX时间戳):http://php.net/manual/en/datetime.formats.compound.php

所以,正确的做法是:

$dateTime = new DateTime('@' . $day, $dateTimeZone); 

或者,我更喜欢:

$dateTime = DateTime($_GET['y']."-".$_GET['m']."-".$_GET['d']); 
1

你发送它的无效的参数。

public DateTime::__construct ([ string $time = "now" [, DateTimeZone $timezone = NULL ]])

构造函数期望A date/time string,而不是发送的UNIX时间戳。因此例外。在您放置的日期周围取消拨打strtotime

现在你或其他人可能会问为什么它会在你的其他日期工作呢?不,即使那样也行不通。试试你的工作日期,看看日期时间日期你得到

echo $dateTime->format("Y-m-d");  

1600-04-01

Fiddle

它没有(和不应该工作),无论是针对因的strtotime通话的日期。

Manual