RonnieT
RonnieT

Reputation: 2203

Calculate date with PHP

How can I set a date range value for each week that gets updated dynamically as time goes on. I want to start the week on Monday and end on Sunday.

Example output would need to be 2011-10-24,2011-10-31

Using the below I am only getting the date of the month vs YYYY-MM-DD

<?php  
   $today = getdate();
   $weekStartDate = $today['mday'] - $today['mon']+1;
   $weekEndDate = $today['mday'] - $today['wday']+7;
   echo "week start date:".$weekStartDate;
   echo "<br/>";
   echo "week end date:".$weekEndDate;
?>

Upvotes: 0

Views: 400

Answers (2)

Phil
Phil

Reputation: 164742

As mentioned in the comments, use DateTime.

<?php
$dt = new DateTime('Monday this week'); // yes, DateTime is that awesome
$interval = new DateInterval('P6D'); // 6 days
?>

<dl>
    <dt>Week start date:</dt>
    <dd><?php echo $dt->format('Y-m-d') ?></dd>

    <dt>Week end date:</dt>
    <dd><?php echo $dt->add($interval)->format('Y-m-d') ?></dd>
</dl>

Upvotes: 2

deceze
deceze

Reputation: 522024

Take advantage of date('N') (day of the week, 1 - 7):

$monday = mktime(0, 0, 0, date('n'), date('j') - (date('N') - 1));
$sunday = mktime(0, 0, 0, date('n'), date('j') - (date('N') - 7));

echo date('Y-m-d', $monday);
echo date('Y-m-d', $sunday);

Upvotes: 0

Related Questions