Domanda

PHP returns an incorrect DateTime value when converting from string back into string.

$dss = "Thu May 16 2013"; //Original date string
$dob = DateTime::createFromFormat('D M n Y', $dss);
$dob->format('D M n Y') => "Thu Apr 4 2014"; //Final output date string

Similar issues occur when using strtotime. Adding or removing date_default_timezone_set had no affect on result, as expected.

For my particular use case of finding number of years between two dates, the problem was resolved using UNIX timestamps and converting to years from there.

I am curious to know the cause of this issue, and the implementation to achieve desired result.

È stato utile?

Soluzione

Why n (Numeric representation of a month, without leading zeros) ? It should be d in your case as its a day,

$dss = "Thu May 16 2013"; 
$dob = DateTime::createFromFormat('D M d Y', $dss);
                                       ^
echo $dob->format('D M d Y'); 

DEMO.

Altri suggerimenti

n is the month number, not the day of month. d is the day of the month.

$dss = "Thu May 16 2013"; //Original date string
$dob = DateTime::createFromFormat('D M d Y', $dss);
echo $dob->format('D M d Y');
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top