0

I am trying to get a calendar up and running. Even though I'm not that great with PHP I managed to get a monthly view calendar up and running quite nicely. However, the goal posts have been moved somewhat and the powers that be would like a weekly view calendar. When they open it will show all of the days of the current week in a table and then have the option to go forward a week and show the next week or back a week. I have struggled with this for many days and my code has gotten over complicated and messy when I am sure there must be a simple solution.

I know that this is a big ask but I will be so grateful if someone could point me in the right direction or give me a simple script for me to build on so I can get back to living my life

This is what I have so far

$week_number = date("W");
$year = date("Y");

if($week_number < 10){
   $week_number = "0".$week_number;
}

for($day=0; $day<=6; $day++)
{
  echo date('d-m-Y', strtotime($year."W".$week_number.$day))." | \n";
}
?>

I managed to get it up and running in a fashion by adding 1 to the $week_number if the 'next_week' button and been clicked (part of a self posting form I haven't included to keep the script simple ) which worked well until the year changed because the week numbers carried on past 53 and I haven't added a way to make $year increase or decrease That's where it all went wrong

tatty27
  • 1,553
  • 4
  • 34
  • 73

1 Answers1

2

DateTime and DateInterval are your friends (PHP 5.3+)

Give this a go:

<?php

$weekModifier = 0;

$date = new DateTime();

if($date->format('N') !== 1) {
    $date->sub(new DateInterval('P'. $date->format('N') . 'D'));
}

$interval = new DateInterval('P'.abs($weekModifier).'W');

if($weekModifier > 0) {
    $date->add($interval);  
} else {
    $date->sub($interval);  
}

for($i = 1; $i <= 7; $i++) {
    echo $date->add(new DateInterval('P1D'))->format('l Y-m-d') . "<br>\n"; 
}

?>

Leaving the week at 0 will use this week. Otherwise, you can simply use 1, 2, 3, -,1 ,-2, -3 etc...

See it in action.

piers.warmers
  • 333
  • 2
  • 6