Home  >  Article  >  Backend Development  >  Why is the Microseconds Field Displaying 000000 When Formatting Dates in m-d-Y H:i:s.u from Milliseconds?

Why is the Microseconds Field Displaying 000000 When Formatting Dates in m-d-Y H:i:s.u from Milliseconds?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-23 19:52:30514browse

Why is the Microseconds Field Displaying 000000 When Formatting Dates in m-d-Y H:i:s.u from Milliseconds?

Getting Date Format m-d-Y H:i:s.u from Milliseconds

In this query, the objective is to format a date string in the format "m-d-Y H:i:s.u" from a Unix timestamp given in milliseconds. However, the result keeps displaying 000000 in the microseconds field.

<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 resolve this issue, the input format "U.u" can be used:

<code class="php">$now = DateTime::createFromFormat('U.u', microtime(true));
echo $now->format("m-d-Y H:i:s.u");</code>

Output:

04-13-2015 05:56:22.082300

This approach utilizes the following format specifiers from the PHP manual:

  • U: Seconds since the Unix Epoch
  • u: Microseconds

Time Zones and microtime()

It's important to note that the createFromFormat() method typically uses the local time zone if one is not explicitly provided. However, since microtime() returns the number of seconds elapsed since the Unix Epoch in UTC, the DateTime object is implicitly initialized to UTC.

If displaying the time for a specific time zone is required, it must be set using setTimeZone() after the initial DateTime creation:

<code class="php">$now->setTimeZone(new DateTimeZone('America/New_York'));</code>

Inputting into MySQL

To input the formatted date string into MySQL, the format should be modified to:

<code class="php">format("Y-m-d H:i:s.u")</code>

The above is the detailed content of Why is the Microseconds Field Displaying 000000 When Formatting Dates in m-d-Y H:i:s.u from Milliseconds?. 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