Raj
Raj

Reputation: 22926

PHP Converting a date to timestamp using DateTime decreases 1 day - weird

Have the following simple PHP code:

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

It outputs

2013-05-04 May 3

But $disp_date should be May 4 right?

Upvotes: 2

Views: 507

Answers (1)

Pekka
Pekka

Reputation: 449415

It's a timezone issue.

strtotime will give you a timezone senstitive timestamp, while createFromFormat with the 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.

There is no need to use strtotime here at all: just do

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

Upvotes: 5

Related Questions