this code always returns 0 in PHP 5.2.5 for microseconds:
format(\"Y-m-d\\TH:i:s.u\") . \"\\n\";
?>
Some answers make use of several timestamps, which is conceptually wrong, and overlapping issues may occur: seconds from 21:15:05.999
combined by microseconds from 21:15:06.000
give 21:15:05.000
.
Apparently the simplest is to use DateTime::createFromFormat() with U.u
, but as stated in a comment, it fails if there are no microseconds.
So, I'm suggesting this code:
function udate($format, $time = null) {
if (!$time) {
$time = microtime(true);
}
// Avoid missing dot on full seconds: (string)42 and (string)42.000000 give '42'
$time = number_format($time, 6, '.', '');
return DateTime::createFromFormat('U.u', $time)->format($format);
}