I have the following code, which gets all 52 past weeks up until the current week. I want to amend it so that it only includes the current year. So it should only show the first 4 weeks of January.
public static function weeks()
{
$nextWeek = strtotime('+1 week');
for($i=0;$i<52;$i++)
{
$date = date('Y-m-d', strtotime('-'.$i.' week'));
$nbDay = date('N', strtotime($date));
$monday = new \DateTime($date);
$sunday = new \DateTime($date);
$monday->modify('-'.($nbDay-1).' days');
$sunday->modify('+'.(7-$nbDay).' days');
if($nextWeek > strtotime($sunday->format('Y-m-d'))) {
$weeks[$monday->format('W')] = $monday->format('j M Y') . ' - ' . $sunday->format('j M Y');
}
}
return $weeks;
}
How can I amend the code?
You could use the date()
with W
for the week of the year as the upper bound for the loop?
public static function weeks()
{
$nextWeek = strtotime('+1 week');
/* change the upper bound of the loop using `date('W')` */
for( $i=0; $i < date('W'); $i++ )
{
$date = date('Y-m-d', strtotime('-'.$i.' week'));
$nbDay = date('N', strtotime($date));
$monday = new \DateTime($date);
$sunday = new \DateTime($date);
$monday->modify('-'.($nbDay-1).' days');
$sunday->modify('+'.(7-$nbDay).' days');
if($nextWeek > strtotime($sunday->format('Y-m-d'))) {
$weeks[$monday->format('W')] = $monday->format('j M Y') . ' - ' . $sunday->format('j M Y');
}
}
return $weeks;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.