Home  >  Article  >  Backend Development  >  How to Retrieve Date Format with Microseconds from Millisecond Timestamp?

How to Retrieve Date Format with Microseconds from Millisecond Timestamp?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-24 02:49:02245browse

How to Retrieve Date Format with Microseconds from Millisecond Timestamp?

Retrieve a Date Format of m-d-Y H:i:s.u from Milliseconds

Problem:

Obtaining a formatted date with microseconds from a UNIX timestamp provided in milliseconds has been an ongoing challenge. Upon attempting to do so, the output consistently yields 000000, even though the expected result should display microseconds.

Solution:

To resolve this issue, the correct input format is U.u, as demonstrated below:

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

Output:

This approach produces the desired output:

04-13-2015 05:56:22.082300

PHP Date Format Interpretation:

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

Additional Notes:

  • Time zones are handled implicitly when using createFromFormat() without specifying a time zone, which initializes the DateTime object to UTC.
  • For specific time zone display, setTimeZone() should be used after object initialization.
  • For MySQL input, the appropriate time format is "Y-m-d H:i:s.u".

The above is the detailed content of How to Retrieve Date Format with Microseconds from Millisecond Timestamp?. 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