DateTime with microseconds

DateTime with microseconds

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

DateTime with microseconds

When working with high-frequency data or precise timing events, standard DateTime objects often fall short. The default PHP implementation truncates fractional seconds, discarding the microseconds that microtime(true) captures. If you are trying to store these values in JSON as floats later on, you quickly realize that converting a truncated integer timestamp back to a float won't restore the lost precision.

The core issue lies in how DateTime::setTimestamp() handles its input. It expects an integer representing seconds since the Unix epoch. Passing a floating-point value like 3.4 results in PHP casting that value to an integer (3) before the object is updated. Consequently, any fractional part is lost immediately upon creation, and formatting the object with the 'u' flag returns 000000.

To retain microsecond precision, you must initialize the DateTime object with a string that explicitly includes the fractional seconds. While parsing a float directly isn't an option without modification, converting your floating-point timestamp into a formatted ISO 8601 string solves the problem with minimal overhead.

Here is a practical approach to creating a DateTime object from a raw float timestamp while preserving microseconds:

$timestamp = microtime(true); // Example: 1678886400.123456

// Extract the integer seconds and the fractional microseconds
$seconds = floor($timestamp);
$microseconds = round(($timestamp - $seconds) * 1000000);

// Create a DateTime object from a string that includes microseconds
// The 'u' modifier ensures microseconds are parsed correctly.
$date = new DateTime("@{$seconds}." . str_pad((string)$microseconds, 6, '0', STR_PAD_LEFT));

echo $date->format('Y-m-d H:i:s.u'); 
// Output: 2023-03-15 17:20:00.123456

This method avoids complex string manipulation by leveraging the @ prefix in the constructor, which expects a timestamp. By manually padding the microseconds to six digits and appending them after the decimal point, you ensure the parser recognizes the fractional seconds. If you omit the padding, trailing zeros might be dropped depending on PHP's internal parsing logic, leading to inconsistent precision.

Once initialized this way, the object behaves exactly like any other DateTime. You can perform arithmetic operations using DateTime::modify() or add(), and when converting back to a string for JSON serialization, you can explicitly request the microseconds:

$jsonData = [
    'timestamp' => $date->format('Y-m-d H:i:s.u'), 
    // Or convert to float if strictly required by your schema
    'float_timestamp' => (float)$date->format('U.u') 
];

Note that DateTime::createFromTimestamp() does not exist in standard PHP; you must always use the constructor with a string or the @ prefixed timestamp format. This distinction is crucial when refactoring legacy code that assumes direct float support.

For Laravel developers, this pattern is particularly relevant when building real-time monitoring dashboards or logging systems where event ordering matters down to the microsecond. While Laravel's global helper functions like now() return standard Carbon instances (which are wrappers around DateTime), they also respect the underlying precision limits if not initialized correctly.

If your application requires storing these values as floats directly in the JSON payload without string formatting, ensure you use a format string that includes the decimal point and microseconds, then cast it to a float. This guarantees that the data sent to your storage layer retains the high-resolution timing information originally captured by microtime(true).

Our network