문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

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');
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top