Home > Backend Development > PHP Tutorial > How to Convert Milliseconds to Date Format m-d-Y H:i:s.u?

How to Convert Milliseconds to Date Format m-d-Y H:i:s.u?

Susan Sarandon
Release: 2024-10-23 18:22:19
Original
1021 people have browsed it

How to Convert Milliseconds to Date Format m-d-Y H:i:s.u?

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

In this article, we'll address a specific issue faced by programmers: formatting a date, including microseconds, from a given UNIX timestamp in milliseconds.

The problem stems from attempting to obtain the desired format using "date("m-d-Y H:i:s.u", $milliseconds/1000)". However, this yields zeros in the microseconds position.

To resolve this issue, we turn to the 'DateTime' class, which allows for more precise date formatting. Specifically, we utilize 'U.u', where 'U' represents seconds since the Unix Epoch and 'u' represents microseconds.

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

This produces an accurate date format, including microseconds.

The PHP manual page describes these date formats in more detail:

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

Note that if you intend to use the formatted date with MySQL, the format should be "Y-m-d H:i:s.u".

The above is the detailed content of How to Convert Milliseconds to Date Format m-d-Y H:i:s.u?. 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