Created
January 23, 2019 10:43
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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