Search code examples
phpdatestrtotimedate-conversion

PHP date() working sporadically


I am converting two strings from one date format to another but I am getting some unusual responses

The two dates i am converting are:

1: 2002-09-23

2: 2010-03-25

The PHP code is as follows for each of the dates:

1:date('d F Y', strtotime((string)$report_display->arr_output_base['Date1']['value']));

2:date("d F Y", strtotime((string)$report_display->arr_input_base['Date2']['value']));

The responses I'm getting are as follows:

1:Sometimes 31 December 1986 which is wrong but then other times I'll get 23 September 2002 which is right

2: is always 25 March 2010


Solution

  • When you know the format, why take risks sending it to strtotime and not use a proper method that uses the exact format?

    $date = DateTime::createFromFormat('Y-m-d', '2002-09-23');
    echo $date->format('d F Y');
    

    That way there is no guesswork involved as to whether a month is a month or it is a day. That will always return the same date no matter what.