In development, getting a timestamp is a common requirement. Generally, the most common timestamp is 10 digits, representing the number of seconds that have passed since January 1, 1970, 00:00:00 UTC. However, in some use cases, we need a more precise timestamp, such as a 13-digit timestamp.
A 13-digit timestamp represents the number of milliseconds that have passed since January 1, 1970, 00:00:00 UTC. Below, we will introduce two methods to get a 13-digit timestamp in PHP:
The microtime() function in PHP can return the microsecond part along with the current timestamp. By passing true as a parameter to microtime(), we get a floating-point number, which we can then manipulate to obtain a 13-digit timestamp.
Code explanation: First, we call microtime(true) to get the microseconds, then multiply it by 1000 to get the millisecond value. Finally, we use intval() to convert it into an integer, resulting in a 13-digit timestamp.
Another method is to use PHP's built-in DateTime class to obtain the 13-digit timestamp. Although this method requires more code, it is more intuitive and easy to understand.
Code explanation: We first create a DateTime object, then use the format() method to get the Unix timestamp (the 10-digit timestamp), multiply it by 1000 to get the milliseconds, and then add the microseconds divided by 1000 to get the precise 13-digit timestamp.
Both of these methods allow you to get a precise 13-digit timestamp. Which one you choose depends on your specific needs and preferences.