Skip to content

Instantly share code, notes, and snippets.

@pasmat
Created January 23, 2019 10:43
Show Gist options
  • Save pasmat/90d07ee19a52ad370d2561a02c349e56 to your computer and use it in GitHub Desktop.
Save pasmat/90d07ee19a52ad370d2561a02c349e56 to your computer and use it in GitHub Desktop.
turn php DateInterval object to SQL date interval calculation by generating SQL code that adds or subtracts given dateinterval from a variable
/**
* turn php DateInterval object to SQL date interval calculation
* by generating SQL code that adds or subtracts given dateinterval
* from a variable
*
* @param DateInterval $interval the interval to subtract or add
* @param $sqlVariable the variable on which the calculation should be performed on, probably now() or some column
* @param string $sqlFunction the function to use to calculate the date, probably either DATE_SUB or DATE_ADD
* @return string sql time calculation
*/
static function phpIntervalToSQL(DateInterval $interval, $sqlVariable, $sqlFunction = "DATE_SUB") {
$dateOffset = [
"YEAR" => intval($interval->y),
"MONTH" => intval($interval->m),
"DAY" => intval($interval->d),
"HOUR" => intval($interval->h),
"MINUTE" => intval($interval->i),
"SECOND" => intval($interval->s)
];
$sqlTimeCalculation = $sqlVariable;
foreach ($dateOffset as $key => $value) {
if ($value !== 0) {
$sqlTimeCalculation = "$sqlFunction($sqlTimeCalculation, INTERVAL $value $key)";
}
}
return $sqlTimeCalculation;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment