format a date in to the format 'yyyy-mm-dd hh:mm:ss.fff' in php

To format a date in the format yyyy-mm-dd hh:mm:ss.fff in PHP, you can use the DateTime class along with the format() method. Here's an example:

main.php
$timestamp = time(); // Get the current timestamp
$date = new DateTime();
$date->setTimestamp($timestamp); // Set the timestamp in the DateTime object
$formatted_date = $date->format('Y-m-d H:i:s.u'); // Format the date
echo $formatted_date; // Output: e.g. 2021-08-11 14:30:45.123456
285 chars
6 lines

In this example, we first get the current timestamp using the time() function. We then create a new DateTime object and set the timestamp in it using the setTimestamp() method. Finally, we format the date using the format() method with the format string 'Y-m-d H:i:s.u', where Y is the year, m is the month, d is the day, H is the hour in 24-hour format, i is the minute, s is the second, and u is the microsecond. The formatted date is then stored in the $formatted_date variable and outputted using echo.

gistlibby LogSnag