Wednesday, 15 August 2012

Get multiple PHP date periods from a range of dates -



Get multiple PHP date periods from a range of dates -

i have array of dates this:

[room 01 - dbl] => array ( [0] => mon 23-06-2014 [1] => tue 24-06-2014 [2] => wed 25-06-2014 [3] => sat 28-06-2014 [4] => sun 29-06-2014 ) [room 02 - twn] => array ( [0] => tue 24-06-2014 [1] => wed 25-06-2014 [2] => sat 28-06-2014 [3] => sun 29-06-2014 )

you can see neither room has date th or friday. want able create date range (either datetime interval object or not - don't mind) each grouping of dates. room 02 - twn should give me 2 date periods - 1 tue-wed , sat-sun. how go this? know how create single date period of time using first , lastly items in array don't know how observe if there gap...

i'm not clear you're trying accomplish. anyway, in general case, can this.

the thought run whole array of items, , if "next" item contiguous candidate interval have, extend interval. else, candidate interval becomes standalone interval, , item failed check gives birth new candidate interval.

you need 2 functions: 1 that, given 2 items, returns whether it's true or false contiguous; other, given 2 items, returns "interval" 2 items extremes.

an empty $items homecoming empty interval.

function build_intervals($items, $is_contiguous, $make_interval) { $intervals = array(); $end = false; foreach ($items $item) { if (false === $end) { $begin = $item; $end = $item; continue; } if ($is_contiguous($end, $item)) { $end = $item; continue; } $intervals[] = $make_interval($begin, $end); $begin = $item; $end = $item; } if (false !== $end) { $intervals[] = $make_interval($begin, $end); } homecoming $intervals; }

for numbers, can use

$interv = build_intervals( array( 1, 2, 3, 5, 6, 9, 10, 11, 13, 17, 18 ), function($a, $b) { homecoming ($b - $a) <= 1; }, function($a, $b) { homecoming "{$a}..{$b}"; } ); print_r($interv);

returns

array ( [0] => 1..3 [1] => 5..6 [2] => 9..11 [3] => 13..13 [4] => 17..18 )

with dates, can maintain them datetime , datetimeintervals. if utilize timestamps, must supply contiguousness criterion that's valid timestamps. can awkward if have 2 timestamps before , after midnight next day. sure, should take times @ around midday (i.e., given 2 dates, timestamps of dates at midday. if they're less 36 hours apart, they're 2 adjacent days.

function($a, $b) { $a_ts = strtotime("{$a} 12:00:00"); $b_ts = strtotime("{$b} 12:00:00"); homecoming ($b - $a) <= (36 * 60 * 60); },

php date datetime time period

No comments:

Post a Comment