Getting Date Format m-d-Y H:i:s.u from Milliseconds using DateTime Library
You aim to format a date, including microseconds, from a UNIX timestamp given in milliseconds. However, you encounter a consistent output of 000000, as seen below:
<code class="php">$milliseconds = 1375010774123; $d = date("m-d-Y H:i:s.u", $milliseconds / 1000); print $d;</code>
Output:
07-28-2013 11:26:14.000000
Solution:
To effectively format your date with microseconds, employ the 'U.u' input format instead:
<code class="php">$now = DateTime::createFromFormat('U.u', microtime(true)); echo $now->format("m-d-Y H:i:s.u");</code>
This code will output:
04-13-2015 05:56:22.082300
Format Specification:
Time Zone Considerations:
Note that createFromFormat() assumes the local time zone if none is specified. However, since microtime() returns UTC time, your DateTime object is implicitly initialized to UTC. If you need to display a specific time zone, set it using setTimeZone() after initialization.
MySQL Database Input:
If inserting the formatted date into a MySQL database, use the following format:
<code class="php">format("Y-m-d H:i:s.u")</code>
The above is the detailed content of How to Format a Date with Microseconds from Milliseconds in PHP. For more information, please follow other related articles on the PHP Chinese website!