this code always returns 0 in PHP 5.2.5 for microseconds:
format(\"Y-m-d\\TH:i:s.u\") . \"\\n\";
?>
How about this?
$micro_date = microtime();
$date_array = explode(" ",$micro_date);
$date = date("Y-m-d H:i:s",$date_array[1]);
echo "Date: $date:" . $date_array[0]."<br>";
Sample Output
2013-07-17 08:23:37:0.88862400
Building on Lucky’s comment, I wrote a simple way to store messages on the server. In the past I’ve used hashes and increments to get unique file names, but the date with micro-seconds works well for this application.
// Create a unique message ID using the time and microseconds
list($usec, $sec) = explode(" ", microtime());
$messageID = date("Y-m-d H:i:s ", $sec) . substr($usec, 2, 8);
$fname = "./Messages/$messageID";
$fp = fopen($fname, 'w');
This is the name of the output file:
2015-05-07 12:03:17 65468400
This seems to work, although it seems illogical that http://us.php.net/date documents the microsecond specifier yet doesn't really support it:
function getTimestamp()
{
return date("Y-m-d\TH:i:s") . substr((string)microtime(), 1, 8);
}
Working from Lucky's comment and this feature request in the PHP bug database, I use something like this:
class ExtendedDateTime extends DateTime {
/**
* Returns new DateTime object. Adds microtime for "now" dates
* @param string $sTime
* @param DateTimeZone $oTimeZone
*/
public function __construct($sTime = 'now', DateTimeZone $oTimeZone = NULL) {
// check that constructor is called as current date/time
if (strtotime($sTime) == time()) {
$aMicrotime = explode(' ', microtime());
$sTime = date('Y-m-d H:i:s.' . $aMicrotime[0] * 1000000, $aMicrotime[1]);
}
// DateTime throws an Exception with a null TimeZone
if ($oTimeZone instanceof DateTimeZone) {
parent::__construct($sTime, $oTimeZone);
} else {
parent::__construct($sTime);
}
}
}
$oDate = new ExtendedDateTime();
echo $oDate->format('Y-m-d G:i:s.u');
Output:
2010-12-01 18:12:10.146625
This method is safer than the accepted answer:
date('Y-m-d H:i:s.') . str_pad(substr((float)microtime(), 2), 6, '0', STR_PAD_LEFT)
Output:
2012-06-01 12:00:13.036613
Update: Not recommended (see comments)
You can specify that your input contains microseconds when constructing a DateTime
object, and use microtime(true)
directly as the input.
Unfortunately, this will fail if you hit an exact second, because there will be no .
in the microtime output; so use sprintf
to force it to contain a .0
in that case:
date_create_from_format(
'U.u', sprintf('%.f', microtime(true))
)->format('Y-m-d\TH:i:s.uO');
Or equivalently (more OO-style)
DateTime::createFromFormat(
'U.u', sprintf('%.f', microtime(true))
)->format('Y-m-d\TH:i:s.uO');