Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the date of a day of the week from a date using PHP?

Tags:

date

php

If I've got a $date YYYY-mm-dd and want to get a specific $day (specified by 0 (sunday) to 6 (saturday)) of the week that YYYY-mm-dd is in.

For example, if I got 2012-10-11 as $date and 5 as $day, I want to get 2012-10-12, if I've got 0 as $day, 2012-10-14

EDIT:
Most of you misunderstood it. I got some date, $date and want to get a day specified by 0-6 of the same week $date is in.

So no, I don't want the day of $date...

like image 632
Zulakis Avatar asked Oct 11 '12 08:10

Zulakis


People also ask

How do you get the day of the week from a date in PHP?

Use strtotime() function to get the first day of week using PHP. This function returns the default time variable timestamp and then use date() function to convert timestamp date into understandable date. strtotime() Function: The strtotime() function returns the result in timestamp by parsing the time string.

How can get current date and day in PHP?

Answer: Use the PHP date() Function You can simply use the PHP date() function to get the current data and time in various format, for example, date('d-m-y h:i:s') , date('d/m/y H:i:s') , and so on.


2 Answers

I think this is what you want.

$dayofweek = date('w', strtotime($date)); $result    = date('Y-m-d', strtotime(($day - $dayofweek).' day', strtotime($date))); 
like image 71
Rezigned Avatar answered Sep 29 '22 19:09

Rezigned


You can use the date() function:

date('w'); // day of week 

or

date('l'); // dayname 

Example function to get the day nr.:

function getWeekday($date) {     return date('w', strtotime($date)); }  echo getWeekday('2012-10-11'); // returns 4 
like image 37
powtac Avatar answered Sep 29 '22 19:09

powtac