Error when trying to create an object DateTime in PHP

前提是你 提交于 2019-12-11 06:39:07

问题


Today I got a project written in PHP. There's an error when I try to show a date in a table data set. This is the statement that generates the error:

$data = new DateTime($registro["previsao de entrega"];

The error message is this:

Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct() Failed to parse time string (2 dez 2011 16:00) at position 0 (2): Unexpected character' in C:\www\fluxo_producao\Telas\TelaFluxoProducao.php:941 Stack trace: #0 C:\www\fluxo_producao\Telas\TelaFluxoProducao.php(941): DateTime->__construct('2 dez 2011 16:0...') #1 {main} thrown in C:\www\fluxo_producao\Telas\TelaFluxoProducao.php on line 941

What I discovered by myself was that if I change the parameter manually to "12 Dec 2006" for example, the function works. But the date the variable is passing is "12 Dez 2006" (Brazilian format, by the way, I'm Brazilian ^_^), and i found too that the default timezone in the server is "America/Sao_Paulo"... What do I have to change in the function or parameters to make it convert the format specified?


回答1:


Verify that you have set your server to the correct time locale:

setlocale(LC_TIME, 'pt_BR');

This is required for strftime() and AFAIK all the date/time related functions and the DateTime class use the same library which will require/respect this setting.




回答2:


It needs to have a closing curly bracket on the end?

$data = new DateTime($registro["previsao de entrega"]);

If this is just a typo it could be the value of $registro["previsao de entrega"] is incorrect, what is it?

You can see allowed value formats here: http://www.php.net/manual/en/datetime.formats.date.php

It will only accept English month values, eg, Dec will work but Dez will not.



来源:https://stackoverflow.com/questions/10030437/error-when-trying-to-create-an-object-datetime-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!