I have an 18 week schedule and a start date:
Total Weeks = 18
Start Date = 9/1/20
I want to know which week number (NOT PHP W
but actual number between 1 and 18
) at any time. So I would pass into a function: Current Date
, Start Date
and Total Weeks
and it would output what current week number it is 1 to 18
I had a what seems like a very convoluted way of doing this but it’s not accurately giving me the week number.
function get_current_week($current_datetime, $start_date, $total_weeks) { $date = date('Y-m-d', strtotime($current_datetime)); $day_of_week = date('N', strtotime($current_datetime)); $today = new DateTime($date); $begin = new DateTime($start_date); $i = 0; // first week number $end_date = clone $begin; $end_date->modify($gl_total_weeks . ' weeks'); $interval = new DateInterval('P1W'); $range = new DatePeriod($begin, $interval, $end_date); $dates = array(); $found = false; foreach($range as $date) { if($date >= $today && !$found) { $found = true; $current_week = ($day_of_week >= 2 ? $i : $i -1); } $dates['Week ' . $i] = $date->format('Y-m-d'); $i++; } if (!$current_week) { $current_week = 1; } return $current_week; }
Thanks for help.
Advertisement
Answer
Without a Dateinterval it becomes easier. Only the difference in days from the start to the current date is required. The rest is some math. The start date is set internally to the Monday of the week. The end date is not controlled. The counting of the weeks continues cyclically.
function getWeekNumber($current_datetime, $start_date, $total_weeks) { $curDate = date_create($current_datetime); $start = date_create($start_date) ->modify('+1 day') ->modify('last Monday') ; $totalDays = $total_weeks * 7; $dayDiff = $start->diff($curDate)->days; return (int)(($dayDiff%$totalDays)/7+1); }
Note: The counting of the weeks starts with 1. For counting from 0 only the +1 in the return line has to be removed.