Php current time in milliseconds

How to get current time in milliseconds in PHP?

This is my implementation, should work on 32bit as well.

Similar Question and Answer

If you want to see real microseconds, you will need to change the precision setting in php.ini to 16.

After that, microsecond(true) gave me the output of 1631882476.298437 .

So I thought that I need to divide the remainder ( 298437 ) with 1000, but in fact, the remainder is 0.298437 of a second. So I need to multiply that by 1000 to get the correct result.

 function get_milliseconds()
public static function formatMicrotimestamp(DateTimeInterface $dateTime): int < return (int) substr($dateTime->format('Uu'), 0, 13); > 
$timeparts = explode(" ",microtime()); $currenttime = bcadd(($timeparts[0]*1000),bcmul($timeparts[1],1000)); echo $currenttime; 

NOTE: PHP5 is required for this function due to the improvements with microtime() and the bc math module is also required (as we’re dealing with large numbers, you can check if you have the module in phpinfo).

$the_date_time = new DateTime($date_string); $the_date_time_in_ms = ($the_date_time->format('U') * 1000) + ($the_date_time->format('u') / 1000); 
public function getTimeToMicroseconds() < $t = microtime(true); $micro = sprintf("%06d", ($t - floor($t)) * 1000000); $d = new DateTime(date('Y-m-d H:i:s.' . $micro, $t)); return $d->format("Y-m-d H:i:s.u"); > 
$d = new DateTime(); echo $d->format("Y-m-d H:i:s.u"); // u : Microseconds 
$d = new DateTime(); echo $d->format("Y-m-d H:i:s.v"); // v : Milliseconds 

Sadee 2664

This works even if you are on 32-bit PHP:

list($msec, $sec) = explode(' ', microtime()); $time_milli = $sec.substr($msec, 2, 3); // '1491536422147' $time_micro = $sec.substr($msec, 2, 6); // '1491536422147300' 

Note this doesn’t give you integers, but strings. However this works fine in many cases, for example when building URLs for REST requests.

If you need integers, 64-bit PHP is mandatory.

Then you can reuse the above code and cast to (int):

list($msec, $sec) = explode(' ', microtime()); // these parentheses are mandatory otherwise the precedence is wrong! // ↓ ↓ $time_milli = (int) ($sec.substr($msec, 2, 3)); // 1491536422147 $time_micro = (int) ($sec.substr($msec, 2, 6)); // 1491536422147300 

Or you can use the good ol’ one-liners:

$time_milli = (int) round(microtime(true) * 1000); // 1491536422147 $time_micro = (int) round(microtime(true) * 1000000); // 1491536422147300 

Use microtime(true) in PHP 5, or the following modification in PHP 4:

array_sum(explode(' ', microtime())); 

A portable way to write that code would be:

function getMicrotime() < if (version_compare(PHP_VERSION, '5.0.0', '<')) < return array_sum(explode(' ', microtime())); >return microtime(true); > 

echo date(‘Y-m-d H:i:s.’) . gettimeofday()[‘usec’];

Shortest version of string variant (32-bit compatibile):

$milliseconds = date_create()->format('Uv'); 

As other have stated, you can use microtime() to get millisecond precision on timestamps.

From your comments, you seem to want it as a high-precision UNIX Timestamp. Something like DateTime.Now.Ticks in the .NET world.

You may use the following function to do so:

Short answer:

64 bits platforms only!

[ If you are running 64 bits PHP then the constant PHP_INT_SIZE equals to 8 ]

Long answer:

If you want an equilvalent function of time() in milliseconds first you have to consider that as time() returns the number of seconds elapsed since the «epoch time» (01/01/1970), the number of milliseconds since the «epoch time» is a big number and doesn’t fit into a 32 bits integer.

Читайте также:  Python scripts sys argv

The size of an integer in PHP can be 32 or 64 bits depending on platform.

The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that’s 32 bits signed). 64-bit platforms usually have a maximum value of about 9E18, except for Windows, which is always 32 bit. PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5.

If you have 64 bits integers then you may use the following function:

microtime() returns the number of seconds since the «epoch time» with precision up to microseconds with two numbers separated by space, like.

The second number is the seconds (integer) while the first one is the decimal part.

The above function milliseconds() takes the integer part multiplied by 1000

then adds the decimal part multiplied by 1000 and rounded to 0 decimals

Note that both $mt[1] and the result of round are casted to int . This is necessary because they are float s and the operation on them without casting would result in the function returning a float .

Finally, that function is slightly more precise than

that with a ratio of 1:10 (approx.) returns 1 more millisecond than the correct result. This is due to the limited precision of the float type ( microtime(true) returns a float). Anyway if you still prefer the shorter round(microtime(true)*1000); I would suggest casting to int the result.

Even if it’s beyond the scope of the question it’s worth mentioning that if your platform supports 64 bits integers then you can also get the current time in microseconds without incurring in overflow.

If fact 2^63 — 1 (biggest signed integer) divided by 10^6 * 3600 * 24 * 365 (approximately the microseconds in one year) gives 292471 .

That’s the same value you get with

echo (int)( PHP_INT_MAX / ( 1000000 * 3600 * 24 * 365 ) ); 

In other words, a signed 64 bits integer have room to store a timespan of over 200,000 years measured in microseconds.

Use microtime . This function returns a string separated by a space. The first part is the fractional part of seconds, the second part is the integral part. Pass in true to get as a number:

var_dump(microtime()); // string(21) "0.89115400 1283846202" var_dump(microtime(true)); // float(1283846202.89) 

Beware of precision loss if you use microtime(true) .

There is also gettimeofday that returns the microseconds part as an integer.

var_dump(gettimeofday()); /* array(4) < ["sec"]=>int(1283846202) ["usec"]=> int(891199) ["minuteswest"]=> int(-60) ["dsttime"]=> int(1) > */ 

The short answer is:

$milliseconds = floor(microtime(true) * 1000); 

More Answer

  • How do i get friendly url in php only?
  • How to Get the inner text of a span in PHP
  • How to get Hello World to work with Spawn-fcgi and php
  • How to get URL string into PHP variable
  • How to create a hyperlink from the data I get from a website with php
  • How do to get specific data from a webpage using PHP
  • How to upload data to use as filter when executing php file to get information from an SQL database?
  • PHP Mail() : how to get more information regarding failure of sending mails using php mail().
  • How to get POSTED data in php script?
  • How to get the drop down box value without submitting in php
  • php + selenium, how to get all tags from one page
  • How can I post and get a php variable
  • How to get comments’ ‘likes’ in detailed format like posts are having in php
  • How to get pattern matching in php array using RegEx
  • How do I get a $_POST value in a PHP file using Javascript and AJAX?
  • How to get php 2 dimensional array in javascript
  • How to get the Sphinx results based on ranking using Sphinx PHP API?
  • PHP — Use GET to include cms (above web root), how to include other files from the cms index?
  • How to get PHP CLI to find its DLL?
  • how i can get parts of web pages by php
  • How do I get dropdowns in a PHP script to submit the form on change?
  • Get formated time for a video duration in php
  • how to get the file permission for a single file in php ftp function
  • How to GET to a clean url using php
  • get current time without page refresh
  • PHP Current Date, Yesterday Time based on DateTime();
  • get the current url with any parameter like # in php
  • How to get all the headers in a PHP script in apache behind a nginx?
  • MongoDB — PHP — How to query and get back intact objects?
  • How to get number of rows with Advantage PHP Extension?
  • How to get php class functions’ comments?
  • How to get players scores for the current week
Читайте также:  Listbox to listbox html

More answer with same ag

  • Error when trying to run a Selenium test with PHPUnit
  • LexikFormFilterBundle loses conditions from relations
  • PHPSESSID Cookie automatically created without calling session_start()
  • PHP — How to capture only one string between delimiters from multiline strings based on defined position
  • How do I push multiple arrays in Javascript and return them from a function?
  • get all values from array inside of another array
  • Symfony2 dumped assets in prod have different code
  • how to set bid modifier for demographic criteria like gender or age range
  • How can I get form content in JSON format from request object using PATCH HTTP method?
  • How to fix PHP Excel export error in application system
  • how to fetch multiple columns containing multiple values using a specific value from single table in PHP/MYSQL
  • Upload and Rename File Plugin in Mooddle
  • Custom buffering of php mysql results — strange issue
  • .htaccess rewrite for multiple variables
  • Laravel scope query wherePivot
  • PHP Trying to get property ‘full_name’ of non-object
  • if statement not returning true even though it should
  • insert image to RTF file using PHP
  • How can I solve an problem with two select statements in one query
  • php authentication display text wrong credentials
  • PHP not all images are showing
  • Remove data from array according to the second one
  • python version of a php curl request
  • how to put .html at the end of url without effecting file type
  • WordPress site «Loaded over https but requested an insecure stylesheet» in reference to google fonts
  • PHP parse_str() function allowing passing shorthand array
  • if statements in while loop?
  • PHP — .htaccess route by article_name
  • I want to merge two arrays while keeping the array keys
  • PHP Xpath Query with Attribute That Has Colon Not Working
  • Apache/php redirect loop
  • Show a preview picture using JavaScript before uploading files
  • jquery plugin in zend framework
  • Laravel image uploads to s3 is 0kb?
  • How can i union these requests in postgreSQL?
  • How to use Discogs API to display similarly named artists?
  • sending mail in PHP not write log file.
  • Unable to get data from database using AJAX & PHP
  • Create linked time input — HTML/PHP/JAVASCRIPT
  • All combinations of two arrays PHP
  • Krajee file input invalid json response
  • Creating a base_url(variable) in the config file — Laravel Config
  • Change One Word Of PHP File Using PHP Script
  • php multidimensional arrays. Change structure
  • Laravel Password reset causing Swift_TransportException error
  • Include form data in the middle of «action» attribute
  • PHP shell_exec() returning different result than SSH Terminal
  • Facebook PHP SDK for Graph API
  • how to organize an unusual connection OneToOne Doctrine2
  • PHP Soap request format differences
Читайте также:  Rainbow background animation css

Источник

microtime

Функция microtime() возвращает текущую метку времени Unix с микросекундами. Эта функция доступна только на операционных системах, в которых есть системный вызов gettimeofday().

Список параметров

Если указано и установлено в TRUE , microtime() возвратит float вместо string , как описано в разделе возвращаемых значений ниже.

Возвращаемые значения

По умолчанию microtime() возвращает string в формате «msec sec», где sec представляет собой количество секунд с начала Эпохи Unix (1 января 1970 0:00:00 GMT), а msec — это количество микросекунд, прошедших после sec.

Если параметр get_as_float установлен в TRUE , то microtime() возвратит результат в вещественном виде ( float ), представляющий собой текущее время в секундах, прошедших с начала Эпохи Unix с точностью до микросекунд.

Примеры

Пример #1 Замер времени выполнения скрипта с помощью функции microtime()

/**
* Простая функция для реализации поведения из PHP 5
*/
function microtime_float ()
list( $usec , $sec ) = explode ( » » , microtime ());
return ((float) $usec + (float) $sec );
>

// Спим некоторое время
usleep ( 100 );

$time_end = microtime_float ();
$time = $time_end — $time_start ;

echo «Ничего не делал $time секунд\n» ;
?>

Пример #2 Замер времени выполнения скрипта в PHP 5

// Спим некоторое время
usleep ( 100 );

$time_end = microtime ( true );
$time = $time_end — $time_start ;

echo «Ничего не делал $time секунд\n» ;
?>

Пример #3 Пример использования microtime() и REQUEST_TIME_FLOAT (начиная с PHP 5.4.0)

// Выбираем время сна случайным образом
usleep ( mt_rand ( 100 , 10000 ));

// Начиная с PHP 5.4.0 в суперглобальном массиве $_SERVER доступно значение REQUEST_TIME_FLOAT.
// Оно содержит временную метку начала запроса с точностью до микросекунд.
$time = microtime ( true ) — $_SERVER [ «REQUEST_TIME_FLOAT» ];

echo «Ничего не делал $time секунд\n» ;
?>

Смотрите также

Источник

Оцените статью