PHP: How to get Sunday and Saturday given a date input?


Question

How can I get the Sunday and Saturday of the week given a specific date?

For example:

input: Monday, September 28, 2009

output should be:

Sunday, September 27, 2009 12:00 AM - Saturday, October 3, 2009 11:59 PM

I am thinking of using the date, strtotime, mktime and time php functions.

If you have a usable function then it is also fine with me.

Thanks in advance :)

Cheers, Mark

1
6
9/28/2009 5:14:57 AM

Accepted Answer

You use strtotime() and date():

<?php
$s = 'Monday, September 28, 2009';
$time = strtotime($s);
$start = strtotime('last sunday, 12pm', $time);
$end = strtotime('next saturday, 11:59am', $time);
$format = 'l, F j, Y g:i A';
$start_day = date($format, $start);
$end_day = date($format, $end);
header('Content-Type: text/plain');
echo "Input: $s\nOutput: $start_day - $end_day";
?>

outputs:

Input: Monday, September 28, 2009
Output: Sunday, September 27, 2009 12:00 PM - Saturday, October 3, 2009 11:59 AM
16
9/28/2009 5:15:00 AM

<?php

date_default_timezone_set('Europe/London');

$datetime = new DateTime("2009-09-23 12:00:00");

// Saturday
$datetime->setISODate(2009, $datetime->format("W"), 6);
print "Saturday:" . $datetime->format(DATE_ATOM) . "\n";
// Sunday
$datetime->setISODate(2009, $datetime->format("W"), 0);
print "Sunday: " . $datetime->format(DATE_ATOM) . "\n";


?>

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon