I've seen some variants on this question but I believe this one hasn't been answered yet.
I need to get the starting date and ending date of a week, chosen by year and week number (not a date)
example:
input:
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.
OPTIONAL: while we are at it, the date format needs to be Y-n-j
(normal date format, no leading zeros.
I've tried editing existing functions that almost did what I wanted but I had no luck so far.
Please help me out, thanks in advance.
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.
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.
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); ?>
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.
Using DateTime class:
function getStartAndEndDate($week, $year) { $dto = new DateTime(); $dto->setISODate($year, $week); $ret['week_start'] = $dto->format('Y-m-d'); $dto->modify('+6 days'); $ret['week_end'] = $dto->format('Y-m-d'); return $ret; } $week_array = getStartAndEndDate(52,2013); print_r($week_array);
Returns:
Array ( [week_start] => 2013-12-23 [week_end] => 2013-12-29 )
Explained:
A shorter version (works in >= php5.3):
function getStartAndEndDate($week, $year) { $dto = new DateTime(); $ret['week_start'] = $dto->setISODate($year, $week)->format('Y-m-d'); $ret['week_end'] = $dto->modify('+6 days')->format('Y-m-d'); return $ret; }
Could be shortened with class member access on instantiation in >= php5.4.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With