Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get any datetime in microseconds from any date in php

Tags:

php

microtime

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.

like image 414
GustavoxD Avatar asked Nov 24 '25 05:11

GustavoxD


2 Answers

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
like image 151
Pitchinnate Avatar answered Nov 25 '25 18:11

Pitchinnate


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).

like image 34
Mike Brant Avatar answered Nov 25 '25 20:11

Mike Brant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!