Question

i'm wondering if there's a way to get any datetime in microseconds.

I was looking forward microtime(), but it just returns the date in the moment.

Anyone knows if is this possible?

I have my date given like: Y-m-d H:i:s.u.

I was thinking about something like (Y-1970)*31556926 + m*151200+d*86400+h*3600+m*60+s.u

but I don't know if that's why i'm a beginner on programming, but i can't think in a way to separate each: Y,m... to do the math.

Would appreciate any help/suggestions.

Was it helpful?

Solution

You can do this with DateTime:

$date = DateTime::createFromFormat('Y-m-d H:i:s.u', '2000-01-01 13:12:12.129817');
echo $date->format('U.u');
//prints: 946728732.129817

OTHER TIPS

What I would do is simply split apart your input format like this:

Y-m-d H:i:s and u

You should be able to do this by exploding on . in your input formatted date string. Then just calculate the UNIX timestamp on the whole second portion. Finally just add your fraction second portion back to the timestamp (via either string concatenation of arithmetic depending on whether you want string or float as result).

No it's not possible. Timestamps are integers internally, describing the seconds from 01.01.1970 GMT. Regardless if you are using a 32 or 64 bit system, the microseconds from 1970 would lead to an overflow as there has much too many of them gone.


You updated the question.. Yes, it is possible to display the current time in microsends using microtime():

$microtime = microtime();
// will return something like:
// 0.40823900 1381181037
// where the first are the micros and the last a regular time stamp
list($micros, $timestamp) = explode(' ', $microtime);

echo date('Y-m-d H:i:s', intval($timestamp)) . '+' 
  . (floatval($micros) * 1000000) . 'msec';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top