Add functions for transferring dates to ints and vice versa

This commit is contained in:
2024-05-03 17:42:32 +02:00
parent 8c1050f40a
commit 63ac1b296e
2 changed files with 116 additions and 0 deletions

View File

@ -928,4 +928,58 @@ final class MD_STD {
return $output;
}
/**
* Transfers a date into an integer. 0000-01-01 > 101; 2001-01-01 > 20010101.
* Needed to store negative dates (BC) in MySQL.
*
* @param string $date Date.
*
* @return integer
*/
public static function date_to_int(string $date):int {
// Edge case: -0000-01-01
if (substr($date, 0, 5) === '-0000') {
return -1 * intval(str_replace("-", "", ltrim($date, "0-")));
}
return intval(date("Ymd", strtotime($date)));
}
/**
* Transfers an integer into a date, reversing the effects of date_to_int.
* 0000-01-01 > 101; 2001-01-01 > 20010101.
* Needed to retrieve negative dates (BC) stored in MySQL.
*
* @param int $date_int Date represented as an integer.
*
* @return string
*/
public static function int_to_date(int $date_int):string {
$dateStr = (string)$date_int;
if (substr($dateStr, 0, 1) === '-') {
$isNegative = true;
$dateStr = substr($dateStr, 1);
}
else $isNegative = false;
if (strlen($dateStr) < 8) {
$dateStr = str_pad($dateStr, 8, "0", STR_PAD_LEFT);
}
$day = substr($dateStr, -2, 2);
$month = substr($dateStr, -4, 2);
$year = substr($dateStr, -8, 4);
return match($isNegative) {
true => '-',
false => '',
} . $year . '-' . $month . '-' . $day;
}
}