dev_musings
dev_musings

Reputation: 1191

PHP strtotime behaviour

The following lines of code returns two different outputs on two different servers A and B:

echo date("M Y", strtotime("2015-01"));
echo date("M Y", strtotime("2015-02"));

The expected output is "Jan 2015" and "Feb 2015" which is correct on the server A.

But the same code on server B returns the output as "Jan 2015" and "Mar 2015".

On debugging, I found that the strtotime function on server B is always returning the timestamp for the current day of every month (today is 29th), which explains why "2015-02" is shown as "March 2015" (since there is no Feb 29, 2015). Yesterday, this code was returning the same output on both servers since Feb 28th is valid and is properly translated to Feb 2015.

So essentially, on server A, the effective code is

 echo date("M Y", strtotime("2015-01-01"));
 echo date("M Y", strtotime("2015-02-01"));

while on server B, the effective code is

echo date("M Y", strtotime("2015-01-29")); //or, strtotime("2015-01-[current day]")
echo date("M Y", strtotime("2015-02-29"));

Why is there this difference between these two servers?

Upvotes: 3

Views: 290

Answers (1)

Federkun
Federkun

Reputation: 36989

This is a problem with different version of php. There is a BC in php 5.2.7, from the documentation:

In PHP 5 prior to 5.2.7, requesting a given occurrence of a given weekday in a month where that weekday was the first day of the month would incorrectly add one week to the returned timestamp. This has been corrected in 5.2.7 and later versions.

Demo

Server A has PHP > 5.2.7, server B has PHP < 5.2.7.

Upvotes: 2

Related Questions