PHP Convertir una fecha en una marca de tiempo usando DateTime disminuye 1 día - extraño

Have the following simple PHP code:

$day = '2013-05-04';
$disp_day = DateTime::createFromFormat('U', strtotime($day));
echo $day . " " . $disp_day->format('F j');

Se produce

2013-05-04 May 3

Pero $disp_date should be May 4 right?

preguntado el 05 de mayo de 13 a las 09:05

@Pekka웃 Please explain... -

1 Respuestas

It's a timezone issue.

strtotime will give you a timezone senstitive timestamp, while createFromFormat con el U parameter will interpret the timestamp as GMT.

  • I'm guessing your time zone is India (GMT + 5.5). Hence, strtotime("2013-05-04") will get you a timestamp that in India is 2013-05-04 00:00. However, in GMT, where it's five and a half hours earlier, the time is 2013-05-03 18:30.

  • You are then passing this Indian timestamp as GMT to CreateFromFormat, leading to the shift.

No hay necesidad de usar strtotime here at all: just do

DateTime::createFromFormat('Y-m-d', $day);

contestado el 05 de mayo de 13 a las 09:05

What is the best possible way to convert a string date 2013-05-04 to a DateTime object without going through timezone hassles? - Lenin Raj Rajasekaran

While you've hit upon the correct solution, the explanation doesn't add up - or maybe I'm just being very slow. - Frutillas

@Strawberry yeah, pondering over the same thing - gimme a minute (I think the OP's actual time zone might be in India, GMT +5.5) - Pekka

@Strawberry I think I got it now - Pekka

But I'm 7 miles from Greenwich, and I get the same result !?! ;-) - Frutillas

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.