Home > Article > Backend Development > Why Does My PHP Code Convert Milliseconds to the Wrong Date?
Converting Milliseconds to Date in PHP
You have a numerical string representing a date as milliseconds since the Unix epoch. Aiming to convert it to the "d-m-Y" format, you encountered a discrepancy between the expected and actual output. This article explores the cause of the issue and provides a solution.
Problem:
Your code below returns "25-11-2008" instead of the expected "02-12-2008":
<code class="php">$mil = 1227643821310; $seconds = $mil / 1000; echo date("d-m-Y", $seconds);</code>
Solution:
Contrary to the assumption, the provided milliseconds value ("1227643821310") does not correspond to "02-12-2008" but to "25-11-2008." This is the correct conversion for the given input.
The timestamp represents the number of milliseconds since 00:00:00 UTC, January 1, 1970. Dividing it by 1000 converts it to seconds, and the date function then formats it into the desired format.
Conclusion:
The issue lies in the incorrect assumption about the milliseconds value. When converting milliseconds to a date, ensure the accuracy of the input and compare the output against the expected value.
The above is the detailed content of Why Does My PHP Code Convert Milliseconds to the Wrong Date?. For more information, please follow other related articles on the PHP Chinese website!