Home  >  Article  >  Backend Development  >  How to Format a Date with Microseconds from Milliseconds in PHP

How to Format a Date with Microseconds from Milliseconds in PHP

Linda Hamilton
Linda HamiltonOriginal
2024-10-24 05:06:02750browse

How to Format a Date with Microseconds from Milliseconds in PHP

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:

  • 'U': Represents the number of seconds since the Unix Epoch.
  • 'u': Represents microseconds.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn