Search code examples
phpdate-conversion

PHP: a simple string to date object conversion fails


I want to convert a string I fetched, into a date object so I can add/substract days to/from it. I tried several methods I read on the net but all failed and I'm completely lost (this should be easy!). This is one example:

echo '11: '.substr($content, 0, 10).'<br/>';
$theDay = new datetime(substr($content, 0, 10));
echo '2: '.$theDay->format('yyyy-mm-dd').'<br/>';
$theDay->modify('+1 day');
echo '21: '.$theDay->format('yyyy-mm-dd').'<br/>';

The output I got was:

11: 2016-02-10
2: 16161616-0202-1010
21: 16161616-0202-1111

The first line shows that the date structure is correct, the second line looks strange! and after adding 1 day, it looks as if it did add 1 day (11 instead of 10) but again it looks strange. What am I missing?


Solution

  • You've got your format string messed up:

    echo '11: '.substr($content, 0, 10).'<br/>';
    $exDay = new datetime(substr($content, 0, 10));
    echo '2: '.$exDay->format('Y-m-d').'<br/>';
    $exDay->modify('+1 day');
    echo '21: '.$exDay->format('Y-m-d').'<br/>';
    

    Output:

    11: 2016-02-10
    2: 2016-02-10
    21: 2016-02-11
    

    See the manual for a complete list of format characters. Relevant for this question are:

    Y   A full numeric representation of a year, 4 digits
    y   A two digit representation of a year
    m   Numeric representation of a month, with leading zeros
    d   Day of the month, 2 digits with leading zeros
    

    I.e., you don't write yyyy for a 4 digit year, but instead Y (same goes for m and d).