将格式作为变量传递时,PHP DateTime返回false

时间:2019-04-04 10:09:42

标签: php datetime

我正在尝试从日期字符串创建日期对象,但是如果我将格式字符串作为变量传递,我将得到false。

我尝试将其作为字符串'Y-m-d'传递,并且按预期方式工作。

工作:

// $date_str = '2019-03-05';

function isValidDateFormat($date_str){
      var_dump(DateTime::createFromFormat('Y-m-d', $date_str));
}

/* prints:

object(DateTime)[64]
  public 'date' => string '2019-03-05 06:07:53' (length=19)
  public 'timezone_type' => int 3
  public 'timezone' => string 'America/Toronto' (length=15)
*/

不起作用:

// $date_str = '2019-03-05';
// $format can be different based on user's choice

function isValidDateFormat($date_str, $format='Y-m-d'){
     var_dump(DateTime::createFromFormat($format, $date_str)); // prints boolean false
}

0 个答案:

没有答案