My code needs to get the weeks along with its first and last day in a month, my code is working but in some months, the first and last day of the last week becomes the combination of the first day of next month and the last day of the current month. Start of week is sunday.
Input is any date in Y-m-d format e.g.(2014-01-05)
, the day won't matter because it will be converted to the first day of that month anyway.
This is the output when the month is january which has a problem:
2014-01-01 2014-01-04
2014-01-05 2014-01-11
2014-01-12 2014-01-18
2014-01-19 2014-01-25
2014-01-26 2014-01-31
2014-02-02 2014-01-31 // here lies the problem
This is the output when the month is February which is correct:
2014-02-01 2014-02-01
2014-02-02 2014-02-08
2014-02-09 2014-02-15
2014-02-16 2014-02-22
2014-02-23 2014-02-28
The functions I'm using:
function getWeeks($from) {
$array = array();
$from = date("Y-m-d", strtotime($from));
$start_date = date('Y-m-01', strtotime($from));
$end_date = date('Y-m-t', strtotime($from));
$end_date1 = date('Y-m-d', strtotime($end_date." + 6 days"));
$week_array = array();
for($date = $start_date; $date < $end_date1; $date = date('Y-m-d', strtotime($date. ' + 7 days')))
{
$getarray = getWeekDates($date, $start_date, $end_date);
$week_array[] = $getarray;
}
return $week_array;
}
function getWeekDates($date, $start_date, $end_date)
{
$week = date('W', strtotime($date));
$year = date('Y', strtotime($date));
$from = date("Y-m-d", strtotime("{$year}-W{$week}+3"));
if($from < $start_date) $from = $start_date;
$to = date("Y-m-d", strtotime("{$year}-W{$week}-6"));
if($to > $end_date) $to = $end_date;
$obj = new stdClass();
$obj->from = $from;
$obj->to = $to;
return $obj;
}
I looked at Get all Work Days in a Week for a given date but it does not help answer my question, because it uses a different implementation. I'd like to use my own implementation.