Home  >  Article  >  Backend Development  >  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
Susan SarandonOriginal
2024-10-23 18:22:19939browse

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");

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!

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