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

How to Format a Date with Microseconds from Milliseconds in PHP

Linda Hamilton
Release: 2024-10-24 05:06:02
Original
846 people have browsed it

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>
Copy after login

Output:

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

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>
Copy after login

This code will output:

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

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>
Copy after login

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!

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