You have timezone issue, because strtotime
function is not timezone aware, and date
is. Instead of setting global timezone, you can set it locally with appending UTC
string to the $sTime
variable, and instead of using date()
use gmdate()
:
// it doesn't matter in which timezone your are, function works with UTC
date_default_timezone_set('Europe/Berlin');
function formatToMySQLTime($sTime, $iInterval) {
switch ($iInterval){
case 1: // 15 minutes;
$iDivider = 15 * 60;
break;
case 2: // 1 hour
$iDivider = 60 * 60;
break;
case 3: // 1 day
$iDivider = 60 * 60 * 24;
break;
}
$U = strtotime($sTime . ' UTC');
$iRoundTime = $U - $U % $iDivider;
return gmdate('Y-m-d H:i:s', $iRoundTime);
}
echo formatToMySQLTime('2013-10-21 03:23:00',1);
echo formatToMySQLTime('2013-10-21 03:23:00',2);
echo formatToMySQLTime('2013-10-21 03:23:00',3);
Update:
Instead of modifying function for every interval, you can make function a little more generic and readable, with the help of DateTime classes, like:
function formatToMySQLTime($sTime, $iInterval) {
$dt = new DateTime($sTime, new DateTimezone('UTC'));
$U = $dt->getTimestamp();
$dt2 = clone $dt;
$interval = DateInterval::createFromDateString($iInterval);
$iDivider = $dt2->add($interval)->getTimestamp() - $U;
$dt->setTimestamp($U - $U % $iDivider);
return $dt->format('Y-m-d H:i:s');
}
echo formatToMySQLTime('2013-10-21 03:23:00', '15 minute');
echo formatToMySQLTime('2013-10-21 03:23:00', '1 hour');
echo formatToMySQLTime('2013-10-21 03:23:00', '1 day');