diff --git a/helpers/class.Date.php b/helpers/class.Date.php index 200319b583..11ef2fde92 100644 --- a/helpers/class.Date.php +++ b/helpers/class.Date.php @@ -277,4 +277,29 @@ public static function getTimeKeys(\DateInterval $interval, \DateTimeInterface $ } return $timeKeys; } + + /** + * Converts from microseconds seconds format of microtime() function to RFC3339_EXTENDED + * @param string|null $microtime + * @return string|null + * @example 0.47950700 1700135696 to 1700135696.47950700 + */ + public static function formatMicrotime(?string $microtime): ?string + { + if ($microtime === null) { + return null; + } + + // Split the string into microseconds and seconds + list($microseconds, $seconds) = explode(' ', $microtime); + + // Show only the numbers after the dot without the integral part + list(, $decimalPart) = explode('.', sprintf('%0.6f', $microseconds)); + //To preserve time zone we are not using createFromFormat() + $date = new DateTime(); + $date->setTimestamp((int)$seconds); + $date->modify('+ ' . $decimalPart . ' microseconds'); + + return $date->format(DateTimeInterface::RFC3339_EXTENDED); + } } diff --git a/test/unit/helpers/DateTest.php b/test/unit/helpers/DateTest.php new file mode 100644 index 0000000000..b87c70dbeb --- /dev/null +++ b/test/unit/helpers/DateTest.php @@ -0,0 +1,50 @@ +assertEquals($expected, $result); + } + + public function microtimeProvider() + { + return [ + ['microtime' => '0.51487900 1701076034', 'expected' => '2023-11-27T09:07:14.514+00:00'], + ['microtime' => '0.81487900 1701078054', 'expected' => '2023-11-27T09:40:54.814+00:00'], + ['microtime' => '0.71487900 1701073054', 'expected' => '2023-11-27T08:17:34.714+00:00'], + ['microtime' => '0.0 1701073054', 'expected' => '2023-11-27T08:17:34.000+00:00'], + ['microtime' => '0 1701073054', 'expected' => '2023-11-27T08:17:34.000+00:00'], + ['microtime' => null, 'expected' => null] + ]; + } +}