Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php - working with dates like "every other week on tuesday"

I have a web scheduling app that I'm currently rewriting and have some questions about how to work with recurring appointments (I know there is no shortage of "what's the best way to do this" when it comes to recurring appts).

So I want to offer recurring appointments where the user can schedule an appointment for a date like Sat, June 2nd, and it should repeat every other week on Saturday for some pre-determined time period (like 1 year).

What php functions can help me determine which date "every other saturday" falls on? I'm attaching a picture of my UI for clarification.

enter image description here

like image 544
Greg Avatar asked Jun 02 '12 07:06

Greg


1 Answers

Personally I'd look to work with DateTime objects and use the DateInterval class.

In your above case, you need to work out the date of the first/next saturday, then just work with a P2W date interval

Basic example

$dow   = 'saturday';
$step  = 2;
$unit  = 'W';

$start = new DateTime('2012-06-02');
$end   = clone $start;

$start->modify($dow); // Move to first occurence
$end->add(new DateInterval('P1Y')); // Move to 1 year from start

$interval = new DateInterval("P{$step}{$unit}");
$period   = new DatePeriod($start, $interval, $end);

foreach ($period as $date) {
    echo $date->format('D, d M Y'), PHP_EOL;
}

/*
Sat, 02 Jun 2012
Sat, 16 Jun 2012
Sat, 30 Jun 2012
Sat, 14 Jul 2012
…
Sat, 20 Apr 2013
Sat, 04 May 2013
Sat, 18 May 2013
Sat, 01 Jun 2013
*/
like image 128
Mark Baker Avatar answered Sep 30 '22 00:09

Mark Baker