Converting string to Date and DateTime

后端 未结 10 1644
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 17:07

If I have a PHP string in the format of mm-dd-YYYY (for example, 10-16-2003), how do I properly convert that to a Date and then a DateTime

10条回答
  •  名媛妹妹
    2020-11-22 17:42

    If you have format dd-mm-yyyy then in PHP it won't work as expected. In PHP document they have below guideline.

    Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

    So, you just can't use as you wish. When your try to use dd/mm/yyyy format with this then it will remove FALSE. You can tweak with the following.

    $date = "23/02/2013";
    $timestamp = strtotime($date);
    if ($timestamp === FALSE) {
      $timestamp = strtotime(str_replace('/', '-', $date));
    }
    echo $timestamp; // prints 1361577600
    

提交回复
热议问题