Matthew Loch
Matthew Loch

Reputation: 59

string modification messes formatting in PHP

$str = date("d")+1 . date("-m") . date("-y");
$date = new DateTime($str);
echo $date->format('y-m-d ');

This works fine, but...

$str = date("d")+1 . date("-m") . date("-y");
$date = new DateTime($str);
echo $date->format('d-m-Y ');

Strangely, both give different dates

I think it's due to the DateTime constructor, but is there an easy workaround for this?

Upvotes: 0

Views: 35

Answers (3)

Marin Sagovac
Marin Sagovac

Reputation: 3992

Instead of manually adding on string date() function you can use object modify:

$str = date("d") . date("m") . date("y");
$time = new DateTime($str);
$time->modify("+1 day");
echo $time->format("d-m-y");

Better way:

$time = new DateTime("+1 day");
echo $time->format("d-m-y");

Upvotes: 0

xdazz
xdazz

Reputation: 160893

Y and y are different.

But the point is, If you just want to get the date of tomorrow, don't write code like that, just use:

$date = new DateTime('+1 day');
echo $date->format('Y-m-d');

If you don't care the time, then you could even use:

$date = new DateTime('tomorrow');

Upvotes: 2

Dave Johnson
Dave Johnson

Reputation: 411

Using an uppercase Y in the date format will give you the four digit year. Using a lowercase y will give you only two digits.

Upvotes: 2

Related Questions