Calculating start of week date in PHP

Associate
Joined
6 Mar 2009
Posts
495
I would like to be able for PHP to hold the date for the current Monday of the week and then reset at the start of the next week. Basically I have a search function where when I click the link " Weeks Data" it will search the database for all the data insert in the current week. So once the next Monday come around it refreshes again. I have used the PHP function to grab todays current date but not a weeks date.

Does anyone know how to do this??
 
Associate
OP
Joined
6 Mar 2009
Posts
495
Depending on wording used, strtotime() isn't always reliable and you can get some undesired results depending on the current date.
Will try and dig out an article that mentions best methods of using strtotime() but alternatively you grab the current date and use the week day (outputs 0 to 6) to calculate the desired day-date.

Edit - http://gamereplays.org/reference/strtotime.php

Thanks for the nice article.

Found code similar online but little confused with the output it produces.

Code:
date = time(); // Change to whatever date you need
// Get the day of the week: Sunday = 0 to Saturday = 6
$dotw = date('w', $date);
// Make it range between Saturday (= 0) and Friday (= 6) by adding one day (and subtracting a week when the result exceeds the week boundaries)
if(++$dotw > 6) $dotw -= 7;
// Calculate the days
$start = $date - ($dotw * 24*60*60); // Substract days for start of week
$end = $start + (6 * 24*60*60); // Add 6 days to the start to get the end of the week
 
Associate
OP
Joined
6 Mar 2009
Posts
495
The DateTime class introduced in PHP 5.2 is very good for things like this.


Code:
$date = new DateTime(); //Instantiate the DateTime class. Note: you can add an argument to this, such as new DateTime('2014-01-01');
$date->modify('this week'); // will get the first day of the week
echo $date->format('Y-m-d'); // Outputs the date in the format, eg, 2014-03-07

Thanks xbenjiiman for this.

Think I have got the starting date of the week and the ending date now by doing the following:
Code:
$date = new DateTime(); 
$date->modify('this week'); 
echo $date->format('Y-m-d'); 

$EndDate = new DateTime();
$EndDate->modify('this week'); 
date_add($EndDate, date_interval_create_from_date_string('6 days'));
echo $EndDate->format('Y-m-d');

Now when using these dates in a query I am getting an error saying that they need to be converted to a string and the DateTime format.

Here the query:
Code:
$QBuild = "SELECT * FROM ($tables[$i]) WHERE Date BETWEEN '$date' AND '$EndDate'";

Any sugestions please??
 
Associate
OP
Joined
6 Mar 2009
Posts
495
$date = new DateTime();
$date->modify('this week');
$startDate = $date->format('Y-m-d');
$date->add(new DateInterval('P6D'));
$endDate = $date->format('Y-m-d');

$QBuild = "SELECT * FROM ($tables[$i]) WHERE Date BETWEEN '$startDate' AND '$endDate'

Thanks xbenjiiman, this did the trick.
 
Back
Top Bottom