PHP Datetime Microseconds Always Returns 0

PHP DateTime microseconds always returns 0

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

DateTime with microseconds

/!\ EDIT /!\

I now use https://github.com/briannesbitt/Carbon, the rest of this answer is just here for historical reasons.

END EDIT

I decided to extend the class DateTime using the tips you all gave me.

The constructor takes a float (from microtime) or nothing (in this case it will be initialized with the current "micro-timestamp").
I also overrided 2 functions that were important : setTimestamp and getTimestamp.

Unfortunately, I couldn't solve the performances issue, although it's not as slow as I thought.

Here's the whole class :

<?php
class MicroDateTime extends DateTime
{
public $microseconds = 0;

public function __construct($time = 'now')
{
if ($time == 'now')
$time = microtime(true);

if (is_float($time + 0)) // "+ 0" implicitly converts $time to a numeric value
{
list($ts, $ms) = explode('.', $time);
parent::__construct(date('Y-m-d H:i:s.', $ts).$ms);
$this->microseconds = $time - (int)$time;
}
else
throw new Exception('Incorrect value for time "'.print_r($time, true).'"');
}

public function setTimestamp($timestamp)
{
parent::setTimestamp($timestamp);
$this->microseconds = $timestamp - (int)$timestamp;
}

public function getTimestamp()
{
return parent::getTimestamp() + $this->microseconds;
}
}

PHP Why does the DateTime diff function always return zero?

There is zero hours difference between the two times so that makes sense. You'll need to test using two times that are further apart to see a value greater than zero here.

Your minutes are incorrect because m is the month identifier. i is for minutes.

$minutes = $diff->i;

php datetime in microseconds

As you found in the docs 'u' is very helpful in this case. http://php.net/manual/en/class.datetime.php#118608

You should be able to use this solution "Y-m-d\TH:i:s.u\Z", but unfortunately you want milliseconds instead of microseconds and you end up with 3 extra 0s. To fix this, just divide the result of 'u' by 1000.

$dt = new DateTime('2016-10-16T22:12:45.104Z');
$helper = $dt->format('u'); //this is factor of 1000 off
$helper /= 1000
$ans = $dt->format('Y-m-d\TH:i:s'); //get the first part of what you
$ans .= "." . $helper . "Z"; //add the milliseconds back on, and Z for good measure

echo $ans . "\n";

DateTime with microseconds for negative timestamps(1970)

Ok, then my solution will be:

function uDate($ts) {
$dts = floor($ts); // integer part
$uts = number_format($ts - $dts, 6, '.', ''); // fraction part
return DateTime::createFromFormat('U\+0.u', "$dts+$uts");
}
function uTime(\DateTimeInteface $dt) { // Reverse action
$dts = $dt->format('U');
$uts = $dt->format('0.u');
return number_format($dts+$uts, 6, '.', '');
}

echo uDate('-128649659.999998')->format('Y-m-d H:i:s.u'), PHP_EOL; // 1965-12-03 23:59:00.000002
echo uDate('-128649660.000002')->format('Y-m-d H:i:s.u'), PHP_EOL; // 1965-12-03 23:58:59.999998
echo uDate('1544639767.999998')->format('Y-m-d H:i:s.u'), PHP_EOL; // 2018-12-12 18:36:07.999998
  • floor function can extract integer part simple, because it rounds always to "nearest smallest integer".

Getting date format m-d-Y H:i:s.u from milliseconds

php.net says:

Microseconds (added in PHP 5.2.2). Note that date() will always generate 000000 since it takes an integer parameter, whereas DateTime::format() does support microseconds if DateTime was created with microseconds.

So use as simple:

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

Recommended and use dateTime() class from referenced:

$t = microtime(true);
$micro = sprintf("%06d",($t - floor($t)) * 1000000);
$d = new DateTime( date('Y-m-d H:i:s.'.$micro, $t) );

print $d->format("Y-m-d H:i:s.u"); // note at point on "u"

Note u is microseconds (1 seconds = 1000000 µs).

Another example from php.net:

$d2=new DateTime("2012-07-08 11:14:15.889342");

Reference of dateTime() on php.net

I've answered on question as short and simplify to author. Please see for more information to author: getting date format m-d-Y H:i:s.u from milliseconds



Related Topics



Leave a reply



Submit