Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 564
marknt15 Avatar asked Sep 28 '09 04:09

marknt15


People also ask

How can I get Saturday and Sunday of the month in php?

$weekends = array_filter($dates, function ($date) { $day = $date->format("l"); return $day === 'Saturday' || $day === 'Sunday'; });

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 do you check a date is Sunday or not in php?

Sample Solution: PHP Code: <? php $dt='2011-01-04'; $dt1 = strtotime($dt); $dt2 = date("l", $dt1); $dt3 = strtolower($dt2); if(($dt3 == "saturday" )|| ($dt3 == "sunday")) { echo $dt3.


1 Answers

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
like image 104
cletus Avatar answered Sep 21 '22 06:09

cletus