Converting string to Date and DateTime

后端 未结 10 1739
伪装坚强ぢ
伪装坚强ぢ 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:37

    If you wish to accept dates using American ordering (month, date, year) for European style formats (using dash or period as day, month, year) while still accepting other formats, you can extend the DateTime class:

    /**
     * Quietly convert European format to American format
     *
     * Accepts m-d-Y, m-d-y, m.d.Y, m.d.y, Y-m-d, Y.m.d
     * as well as all other built-in formats
     * 
     */
    class CustomDateTime extends DateTime 
    {
      public function __construct(string $time="now", DateTimeZone $timezone = null) 
      {
        // convert m-d-y or m.d.y to m/d/y to avoid PHP parsing as d-m-Y (substr avoids microtime error)
        $time = str_replace(['-','.'], '/', substr($time, 0, 10)) . substr($time, 10 );
    
        parent::__construct($time, $timezone);
      }
    }
    
    // usage:
    $date = new CustomDateTime('7-24-2019');
    print $date->format('Y-m-d');
    
    // => '2019-07-24'
    

    Or, you can make a function to accept m-d-Y and output Y-m-d:

    /**
     * Accept dates in various m, d, y formats and return as Y-m-d
     * 
     * Changes PHP's default behaviour for dates with dashes or dots.
     * Accepts:
     *   m-d-y, m-d-Y, Y-m-d,
     *   m.d.y, m.d.Y, Y.m.d,
     *   m/d/y, m/d/Y, Y/m/d,
     *   ... and all other formats natively supported 
     * 
     * Unsupported formats or invalid dates will generate an Exception
     * 
     * @see https://www.php.net/manual/en/datetime.formats.date.php PHP formats supported
     * @param  string $d various representations of date
     * @return string    Y-m-d or '----' for null or blank
     */
    function asYmd($d) {
      if(is_null($d) || $d=='') { return '----'; }
    
      // convert m-d-y or m.d.y to m/d/y to avoid PHP parsing as d-m-Y
      $d = str_replace(['-','.'], '/', $d);
    
      return (new DateTime($d))->format('Y-m-d');
    }
    
    // usage:
    
    
    
    // or
    
    
    

提交回复
热议问题