user794846
user794846

Reputation: 1931

DateTime object How to change the year to be the current year

I have a list of birthdates and I want to figure out what day of the week each birthday will be for this year.

Is there an easy way to modify the DateTime object to change the year to be the current year? That way I can use that to get the day of the week etc.

Say this is my date of birth object:

$dob = DateTime::createFromFormat('Y-m-d', '1986-07-26');

How do I modify that to be the current year or create a new object from it with the same date in the current year?

Once I have done that, I then just do something like:

$test = $dob->format('l');

Upvotes: 1

Views: 478

Answers (2)

Faisal Rahman Avash
Faisal Rahman Avash

Reputation: 1256

You can either use modify() to increment/decrement to current year or use setDate() like this:

$dob->setDate((int) date("Y"), (int)$dob->format('m'), (int)$dob->format('d'));

Upvotes: 0

remeus
remeus

Reputation: 2424

You can modify the date directly.

$today = new DateTime();
$dob->setDate($today->format('Y'), $dob->format('m'), $dob->format('d'));

echo $dob->format('Y-m-d'); // 2019-07-26

Upvotes: 0

Related Questions