How to Returns the current Unix timestamp with microseconds in PHP ?


In PHP, we can use the microtime() function to get the current Unix timestamp with microseconds. The microtime() function returns the current Unix timestamp with microseconds as a float value.

Here's an example:

$timestamp = microtime(true);
echo $timestamp;

Output:

1626847583.123456

In the above example, microtime(true) returns the current Unix timestamp with microseconds as a float value, which is then assigned to the $timestamp variable. Finally, the $timestamp variable is printed using the echo statement.

Alternatively, we can also use the DateTime class to get the current Unix timestamp with microseconds. Here's an example:

$datetime = new DateTime();
$timestamp = $datetime->format('U.u');
echo $timestamp;

Output:

1626847583.123456

In the above example, we create a new DateTime object, which represents the current date and time. We then use the format() method to format the date and time as a Unix timestamp with microseconds. The U format character represents the Unix timestamp, and the u format character represents the microseconds. Finally, the formatted timestamp is assigned to the $timestamp variable and printed using the echo statement.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.