Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Start and End Days for a Given Week in PHP

Tags:

php

datetime

I'm trying to get the week range using Sunday as the start date, and a reference date, say $date, but I just can't seem to figure it out.

For example, if I had $date as 2009-05-01, I would get 2009-04-26 and 2009-05-02. 2009-05-10 would yield 2009-05-10 and 2009-05-16. My current code looks like this (I can't remember where I lifted it from, as I forgot to put down the url in my comments):

function x_week_range(&$start_date, &$end_date, $date) {     $start_date = '';     $end_date = '';     $week = date('W', strtotime($date));     $week = $week;      $start_date = $date;      $i = 0;     while(date('W', strtotime("-$i day")) >= $week) {         $start_date = date('Y-m-d', strtotime("-$i day"));         $i++;     }      list($yr, $mo, $da) = explode('-', $start_date);      $end_date = date('Y-m-d', mktime(0, 0, 0, $mo, $da + 6, $yr)); } 

I realized all it did was add 7 days to the current date. How would you do this?

like image 745
Zahymaka Avatar asked May 29 '09 00:05

Zahymaka


People also ask

How can I get a week start and end in php?

getStartAndEndDate($week, $year); output: $return[0] = $firstDay; $return[1] = $lastDay; The return value will be something like an array in which the first entry is the week starting date and the second being the ending date.

How can I get last week start and end date in php?

date("m/d/Y", strtotime("last week monday")); date("m/d/Y", strtotime("last week sunday")); It will give the date of Last week's Monday and Sunday.

How can I get start date and end date in php?

php function days($date1, $date2) { $date1 = strtotime($date1); $date2 = strtotime($date2); return ($date2 - $date1) / (24 * 60 * 60); } $date1 = '20100820'; $date2 = '20100930'; echo days($date1, $date2); ?>


1 Answers

I would take advantange of PHP's strtotime awesomeness:

function x_week_range(&$start_date, &$end_date, $date) {     $ts = strtotime($date);     $start = (date('w', $ts) == 0) ? $ts : strtotime('last sunday', $ts);     $start_date = date('Y-m-d', $start);     $end_date = date('Y-m-d', strtotime('next saturday', $start)); } 

Tested on the data you provided and it works. I don't particularly like the whole reference thing you have going on, though. If this was my function, I'd have it be like this:

function x_week_range($date) {     $ts = strtotime($date);     $start = (date('w', $ts) == 0) ? $ts : strtotime('last sunday', $ts);     return array(date('Y-m-d', $start),                  date('Y-m-d', strtotime('next saturday', $start))); } 

And call it like this:

list($start_date, $end_date) = x_week_range('2009-05-10'); 

I'm not a big fan of doing math for things like this. Dates are tricky and I prefer to have PHP figure it out.

like image 195
Paolo Bergantino Avatar answered Sep 22 '22 11:09

Paolo Bergantino