New Create DateTime microseconds in PHP 8.4
New Create DateTime microseconds in PHP 8.4
Video Lesson: Create DateTime microseconds in PHP 8.4
PHP 8.4 introduces two new methods (getMicrosecond and setMicrosecond) for handling microseconds in DateTime objects.
Published 1 week ago
Share with colleagues:
Lesson Content
PHP 8.4 introduces two convenient methods for handling microseconds in DateTime objects: getMicrosecond()
and setMicrosecond()
.
Before PHP 8.4, working with microseconds was clunky. You had to extract values using string formatting or reset the entire time:
<?php
// Old way - getting microseconds
$date = new DateTimeImmutable();
$microseconds = (int) $date->format('u');
echo $microseconds.PHP_EOL;
// Old way - setting microseconds (very verbose)
$date = $date->setTime(
(int) $date->format('G'), // hour
(int) $date->format('i'), // minute
(int) $date->format('s'), // second
628115, // microsecond
);
$microseconds = (int) $date->format('u');
echo $microseconds.PHP_EOL;
PHP 8.4 simplifies this with dedicated methods:
<?php
// Get microseconds
$date = new DateTimeImmutable();
$microseconds = $date->getMicrosecond();
echo $microseconds; // Outputs a value between 0-999999
// Set microseconds
$date = new DateTime();
$date->setMicrosecond(628115);
$microseconds = $date->getMicrosecond();
echo $microseconds.PHP_EOL; // 628115
When setting microseconds, values must be between 0 and 999999. Anything outside this range throws a DateRangeError
:
try {
$date->setMicrosecond(1000000); // Too large
} catch (DateRangeError $e) {
echo $e->getMessage();
// DateTime::setMicrosecond(): Argument #1 ($microsecond)
// must be between 0 and 999999, 1000000 given
}
Microseconds are perfect for high-precision timing, like measuring function execution time:
<?php
// Start time
$start = new DateTime();
// Run some process
array_fill(0, 1000000, 'test');
// End time
$end = new DateTime();
// Calculate difference
$startMicro = $start->getMicrosecond();
$endMicro = $end->getMicrosecond();
$microDiff = $endMicro - $startMicro;
echo "Process took approximately $microDiff microseconds";
These new methods make working with high-precision timestamps much simpler and more readable than before.