<?php
function align_timestamp_to($stamp, $unit, $past){ // timestamp, unit string, start/end
static $modes = array(
'year' => 'last year',
'week' => 'last monday',
'month' => 'first day of this month',
'hour' => 'last hour',
'minute' => 'last minute',
);
// TODO error out if unknown $unit
$offset = $modes[$unit];
if($past == 'end')$offset = '+1 '.$unit.' '.$offset.' -1 second';
return strtotime($offset, $stamp);
}
foreach(array(
array(strtotime('4 Apr 2012'), 'year', 'start'),
array(strtotime('4 Apr 2012'), 'year', 'end'),
array(strtotime('4 Apr 2012'), 'month', 'start'),
array(strtotime('4 Apr 2012'), 'month', 'end'),
array(strtotime('4 Apr 2012'), 'week', 'start'),
array(strtotime('4 Apr 2012'), 'week', 'end'),
) as $test)echo date('r', $test[0]).' aligned '.$test[2].' of '.$test[1].' yields '.date('r', align_timestamp_to($test[0], $test[1], $test[2])).'<br/>';
preferences:
29.71 ms | 402 KiB | 5 Q