tomsihap
tomsihap

Reputation: 1769

Laravel + DateTime : date property isn't defined?

This will work well (meaning I can work on $today->date here without issues) :

$today = new \DateTime('NOW');
$today->format('Ymd');
var_dump($today);
$date = date('Ymd', strtotime($today->date . ' +1 Weekday'));

But this raises an error :

$today = new \DateTime('NOW');
$today->format('Ymd');
var_dump($today);
$date = date('Ymd', strtotime($today->date . ' +1 Weekday'));

The error being :

Undefined property: DateTime::$date

This is strange ! It seems that $today (DateTime object) will work as an object, or at least its date property will exists, only if it is being called (in a var_dump here...) once before.

What am I doing wrong ?


Note : I've been doing my homework, this answer tells that there is no ->date property in a DateTime object.

But $today->date being working in my example and var_dump being returning this :

object(DateTime)#493 (3) { 
   ["date"]=> string(26) "2016-12-09 11:51:00.000000"
   ["timezone_type"]=> int(3)
   ["timezone"]=> string(3) "UTC"
}

Of course, using date as an array key will not work neither :

Cannot use object of type DateTime as array

Note : Not answering the question but if needed by someone having the issue, one can have the string value of the DateTime object this way (format of your own) :

$today = new \DateTime('NOW');
$date = $today->modify('+1 Weekday')->format('Ymd');

Upvotes: 2

Views: 1287

Answers (1)

Mikhail.root
Mikhail.root

Reputation: 832

In Laravel there's a standard of using Carbon class for handling date-time manipulations. It's a wrapper around standard PHP DateTime object but enchanced with a lot's of usefull methods http://carbon.nesbot.com/docs/ So you can get Now like

$now=Carbon::now();
$now->addDay(); // or
$now->addDays(1);  // to add one or whatever days to current

Note modifiers on Carbon object like addDays(1) will change original object, so if you need to left it untouched for some puprose just clone it first

$another_date=clone($now); 
$another_date->addDays(1); // $now still untouched

to format is as a string use

 $now->format('Y m d');  

or

 $now->toDateString();                          // 2016-12-10
 $now->toFormattedDateString();                 // Dec 10, 2016

Formatting is the same as for DateTime in PHP.

Upvotes: 1

Related Questions