oxk4r
oxk4r

Reputation: 517

PHP - How to fix date_format() error 'boolean given, instead of DateTimeInterface'?

I'm getting this error: "Warning: date_format() expects parameter 1 to be DateTimeInterface, boolean given in C:...\myFile.php on line 24"

I've tried that code using strtotime instead of time():

$strDate = time();
$str = strtotime($strDate);
$date = date_create($str);
echo date_format($date, "Y/m/d");

And works: //--> 2018/12/31

But can't understand why, because both strtotime, and time return same Unix timestamps.

$dtObj = date_create(time(), timezone_open("Europe/Oslo"));
echo $dtObj . '</br>'; // Works ok
date_format($dtObj, "d-m-Y"); // This throws error

I expected the same result wiht both codes. Any clue about what's happening?

Upvotes: 1

Views: 3034

Answers (1)

Paolo
Paolo

Reputation: 15827

date_create() expects as first parameter a string representing date and time.

Passing a number as you do (you pass time() that return the unix timestamp) will result in date_create returning false that of course cannot be parsed by date_format().

You can read the documentation to see how the data string can be formatted.

You can pass "now" if you want to create a DateTime object set to the present moment.

$dtObj = date_create( "now", timezone_open("Europe/Oslo"));
echo date_format($dtObj, "d-m-Y") . "<br>";

Upvotes: 3

Related Questions