Skip to content
Advertisement

Get first day date of the week on a given date PHP

I have a date 2015-12-16

i want to get the date of the first day’s date for the current week of my date

here 2015-12-16 is in the week 51 of the year then i want to get the first day’s date of the week 51 ( 2015-12-14 here)

how could i do it ? thank you

EDIT: it must work when there are 53 weeks in the year (like in 2015 for example)

Advertisement

Answer

You can do the following:

 $dateTime = new DateTime("2015-12-16");

 $weekNo = $dateTime->format("W");

 $newDate = new DateTime();
 $newDate->setISODate($dateTime->format("Y"), $weekNo);

Example:

http://sandbox.onlinephpfunctions.com/code/281a1ac298bfee8be421e333e4b7e92c6bb44d65

Since the above is a bit off in some cases here’s something more reliable:

 $dateTime = new DateTime("2016-01-01");
 $dateTime->sub(new DateInterval("P".($dateTime->format("w")-1)."D"));  //Since the weekdays are 1-based.

Example: http://sandbox.onlinephpfunctions.com/code/c5cb0f077fa77974d977ddbffa6bc0b61f9d7851

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement