Adding years to a date resets to 1970-01-01

后端 未结 5 1029
悲&欢浪女
悲&欢浪女 2020-12-11 09:47
$somedate = \"1980-02-15\";
$otherdate = strtotime(\'+1 year\', strtotime($somedate));
echo date(\'Y-m-d\', $otherdate);

outputs

19         


        
5条回答
  •  借酒劲吻你
    2020-12-11 10:31

    strtotime() uses a unix timestamp, so it overflows if it attempts to calculate years beyond 2038 and reverts back to 1970.

    To get around this, use the DateTime object. http://php.net/manual/en/book.datetime.php

    To add a period of time to a DateTime object, use DateTime::add, which takes a DateInterval as a parameter. http://php.net/manual/en/datetime.add.php http://www.php.net/manual/en/class.dateinterval.php

    $date = new DateTime("1980-02-15");
    if (method_exists("DateTime", "add")) {
        $date->add(new DateInterval("Y75"));
    } else {
        $date->modify("+75 years");
    }
    echo $date->format("Y-m-d");
    

提交回复
热议问题