How to Get Date Format m-d-Y H:i:s.u from Milliseconds in PHP?

Susan Sarandon
Release: 2024-10-24 02:31:02
Original
626 people have browsed it

How to Get Date Format m-d-Y H:i:s.u from Milliseconds in PHP?

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

Imagine you want a formatted date, complete with microseconds, from a UNIX timestamp measured in milliseconds. But you repeatedly end up with 000000 and a result like this:

07-28-2013 11:26:14.000000
Copy after login

The Solution

The solution involves using the input format U.u:

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

This gives the following output:

04-13-2015 05:56:22.082300
Copy after login

Understanding the Format

From the PHP manual for date formats, we have:

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

Time Zone Considerations

Normally, createFromFormat() uses the local time zone if one is not specified. However, microtime() returns elapsed seconds since the Unix Epoch in UTC, so the DateTime object is implicitly initialized to UTC. This is fine for server-internal tasks, but if you need to display the time for a specific time zone, set the time zone accordingly after initializing the object. Use the setTimeZone() method for this purpose.

Additional Notes

  • To input into MySQL, use the following format: format("Y-m-d H:i:s.u")
  • The original answer was improved by adding number_format() to the line, which fixes the case with exact seconds.

The above is the detailed content of How to Get Date Format m-d-Y H:i:s.u from Milliseconds in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!