patskot
patskot

Reputation: 165

Laravel calculating previous and next recurring date

I am in the process of setting up a recurring event model e.g.

event: {
    id: 1,
    name: 'event name',
    date: '2017-04-22', // First occurrence of the event
    frequency: 'weekly'
}

The goal is to be able to calculate the previous and next occurrence of the event based on a given date e.g.

getLastOccurrance('2017-06-29') // Would return '2017-06-24'
getNextOccurrance('2017-06-29') // Would return '2017-07-01'

Would be awesome if I could somehow return the previous and next date in an eloquent query with the event. Something like:

event: {
    id: 1,
    name: 'event name',
    date: '2017-04-22',
    frequency: 'weekly',
    last_event: '2017-06-24',
    next_event: '2017-07-01'
}

Any advice would be much appreciated, I may be going about things completely wrong. Hopefully I have explained the desired result well enough. Thanks in advance to anyone who can help.

Upvotes: 0

Views: 1074

Answers (2)

patskot
patskot

Reputation: 165

I ended up using php's DateInterval and DatePeriod functions to get an array of dates. Here's an example:

  $start      = new DateTime( '2018-08-01' ); // Date to increment from
  $end        = new DateTime( '2018-10-01' ); // Date to increment up to
  $interval   = new DateInterval("P2D"); // The increment interval, 2 days
  $days       = new DatePeriod($start, $interval, $end);

  foreach($days as $day)...

Upvotes: 1

Sagar Gautam
Sagar Gautam

Reputation: 9389

Use Carbon,

$next_event = Carbon::parse('2017-04-22')->addDays(7);
$last_event = Carbon::parse('2017-04-22')->addDays(-7);

You can use addWeeks function as well like: addWeeks(1) and addWeeks(-1)

Upvotes: 0

Related Questions