php time с миллисекундами
How to get current time in milliseconds in PHP?
15 Answers 15
The short answer is:
90%: substr(microtime(true) * 1000, 0, 13);
There is also gettimeofday that returns the microseconds part as an integer.
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.
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
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.
That’s the same value you get with
In other words, a signed 64 bits integer have room to store a timespan of over 200,000 years measured in microseconds.
Как узнать текущее время в миллисекундах в PHP?
Короткий ответ является:
Существует также, gettimeofday что возвращает часть микросекунд в виде целого числа.
Короткий ответ:
Только 64-битные платформы!
[ Если вы используете 64-битный PHP, то константа PHP_INT_SIZE равна 8 ]
Длинный ответ:
Размер целого числа в PHP может быть 32 или 64 бит в зависимости от платформы.
Если у вас 64-разрядные целые числа, вы можете использовать следующую функцию:
Вышеуказанная функция milliseconds() принимает целую часть, умноженную на 1000
затем добавляет десятичную часть, умноженную на 0 1000 и округленную до 0
Наконец, эта функция немного точнее, чем
что с соотношением 1:10 (прибл.) возвращает на 1 миллисекунду больше, чем правильный результат. Это связано с ограниченной точностью типа с плавающей точкой ( microtime(true) возвращает значение с плавающей точкой). В любом случае, если вы по-прежнему предпочитаете более короткое, round(microtime(true)*1000); я бы предложил int использовать результат.
Даже если это выходит за рамки вопроса, стоит упомянуть, что, если ваша платформа поддерживает 64-битные целые числа, вы также можете получить текущее время в микросекундах без переполнения.
Это то же значение, которое вы получаете с
Другими словами, 64-разрядное целое число со знаком может хранить промежуток времени более 200 000 лет, измеренный в микросекундах.
microtime
(PHP 4, PHP 5, PHP 7, PHP 8)
microtime — Возвращает текущую метку времени Unix с микросекундами
Описание
Функция microtime() возвращает текущую метку времени Unix с микросекундами. Эта функция доступна только на операционных системах, в которых есть системный вызов gettimeofday().
Список параметров
Возвращаемые значения
Примеры
Пример #1 Замер времени выполнения скрипта
// Спим некоторое время
usleep ( 100 );
Пример #2 Пример использования microtime() и REQUEST_TIME_FLOAT
Смотрите также
User Contributed Notes 20 notes
All these timing scripts rely on microtime which relies on gettimebyday(2)
This can be inaccurate on servers that run ntp to syncronise the servers
time.
For timing, you should really use clock_gettime(2) with the
CLOCK_MONOTONIC flag set.
This returns REAL WORLD time, not affected by intentional clock drift.
This may seem a bit picky, but I recently saw a server that’s clock was an
hour out, and they’d set it to ‘drift’ to the correct time (clock is speeded
up until it reaches the correct time)
Those sorts of things can make a real impact.
Any solutions, seeing as php doesn’t have a hook into clock_gettime?
Here is a solution to easily calculate the execution time of a script without having to alter any configuration parameter. It uses the former way of getting microseconds.
It is important to note that microtime(TRUE) does NOT always return a float (at least in PHP 5.x; I have not tested 7.x). If it happens to land on an exact second, it returns an integer instead.
The description of «msec», in this documentation, is very bad.
It is NOT the microseconds that have elapsed since «sec» (if so, it should be given as an integer, without the «0.» in the beginning of the string).
It IS the fractional part of the time elapsed since «sec», with microseconds (10E-6) precision, if the last «00» are not considered significant».
If the last two digits are significant, then we would have a precision of 10E-8 seconds.
mixed mini_bench_to(array timelist[, return_array=false])
return a mini bench result
-the timelist first key must be ‘start’
-default return a resume string, or array if return_array= true :
‘total_time’ (ms) in first row
details (purcent) in next row
The function to include :
Using microtime() to set ‘nonce’ value:
Out of the box, microtime(true) will echo something like:
Which is obviously less than microsecond accuracy. You’ll probably want to bump the ‘precision’ setting up to 16 which will echo something like:
*Internally* it will be accurate to the six digits even with the default ‘precision’, but a lot of things (ie. NoSQL databases) are moving to all-text representations these days so it becomes a bit more important.
* 14 at the time of writing
//timestamp in milliseconds:
intval ( microtime ( true )* 1000 )
//timestamp in microseconds:
intval ( microtime ( true )* 1000 * 1000 )
//timestamp in nanoseconds:
intval ( microtime ( true )* 1000 * 1000 * 1000 )
While doing some experiments on using microtime()’s output for an entropy generator I found that its microsecond value was always quantified to the nearest hundreds (i.e. the number ends with 00), which affected the randomness of the entropy generator. This output pattern was consistent on three separate machines, running OpenBSD, Mac OS X and Windows.
The solution was to instead use gettimeofday()’s output, as its usec value followed no quantifiable pattern on any of the three test platforms.
A convenient way to write the current time / microtime as formatted string in your timezone as expression?
DateTime now is: 2018-06-01 14:54:58 Europe/Berlin
Microtime now is: 180601 14:54:58.781716 Europe/Berlin
I have been getting negative values substracting a later microtime(true) call from an earlier microtime(true) call on Windows with PHP 5.3.8
$time_start = micro_time ();
sleep ( 1 );
$time_stop = micro_time ();
I use this for measure duration of script execution. This function should be defined (and of couse first call made) as soon as possible.
?>
However it is true that result depends of gettimeofday() call. ([jamie at bishopston dot net] wrote this & I can confirm)
If system time change, result of this function can be unpredictable (much greater or less than zero).
Of the methods I’ve seen here, and thought up myself, to convert microtime() output into a numerical value, the microtime_float() one shown in the documentation proper(using explode,list,float,+) is the slowest in terms of runtime.
I implemented the various methods, ran each in a tight loop 1,000,000 times, and compared runtimes (and output). I did this 10 times to make sure there wasn’t a problem of other things putting a load spike on the server. I’ll admit I didn’t take into account martijn at vanderlee dot com’s comments on testing accuracy, but as I figured the looping code etc would be the same, and this was only meant as a relative comparison, it should not be necessary.
Get date time with milliseconds
Test accuracy by running it in a loop.
//Function to convert microtime return to human readable units
//функция для конвертации времени, принимает значения в секундах
Как получить текущее время в миллисекундах в PHP?
time() в секундах – есть ли один миллисекунды?
Короткий ответ :
Существует также gettimeofday() который возвращает часть микросекунды как целое число.
Как и другие, вы можете использовать microtime() для получения миллисекундной точности на microtime() времени.
Для этого вы можете использовать следующую функцию:
Короткий ответ:
Только 64-битные платформы!
Длительный ответ:
Если вы хотите получить эквивалентную функцию time() в миллисекундах, сначала нужно учитывать, что по мере того, как time() возвращает количество секунд, прошедших со времени «эпохи» (01/01/1970), количество миллисекунд с «эпохи» time «является большим числом и не вписывается в 32-битное целое число.
Размер целого числа в PHP может быть 32 или 64 бит в зависимости от платформы.
Размер целого зависит от платформы, хотя максимальное значение около двух миллиардов – это обычное значение (это 32 бита). 64-разрядные платформы обычно имеют максимальное значение около 9E18, за исключением Windows, которая всегда 32 бит. PHP не поддерживает целые числа без знака. Целочисленный размер может быть определен с использованием константы PHP_INT_SIZE и максимального значения с использованием константы PHP_INT_MAX с PHP 4.4.0 и PHP 5.0.5.
Если у вас есть 64-битные целые числа, вы можете использовать следующую функцию:
microtime() возвращает количество секунд с момента «эпохи» с точностью до микросекунд с двумя номерами, разделенными пробелом, например …
Второе число – это секунда (целое число), предшествующее десятичной части.
Функция milliseconds принимает целочисленную часть, умноженную на 1000
и добавляет десятичную часть, умноженную на 1000 и округленную до 0 десятичных знаков
Наконец, эта функция несколько точнее, чем
что с отношением 1:10 (приблизительно) возвращает на 1 миллисекунду больше, чем правильный результат. Это связано с ограниченной точностью типа float ( microtime(true) возвращает float). В любом случае, если вы по-прежнему предпочитаете более короткий round(microtime(true)*1000); Я бы предложил лить в результат.
Даже если это выходит за рамки вопроса, стоит упомянуть, что если ваша платформа поддерживает 64-битные целые числа, то вы также можете получить текущее время в микросекундах без переполнения.
Это то же значение, возвращаемое echo PHP_INT_MAX / (1000000*3600*24*365);
Другими словами, целое число со знаком имеет место для хранения временного интервала более 200000 лет, измеренного в микросекундах.
Используйте microtime(true) в PHP 5 или следующую модификацию в PHP 4:
Портативный способ написать этот код:
ПРИМЕЧАНИЕ. Для этой функции требуется PHP5 из-за улучшений с microtime (), а также необходим математический модуль bc (поскольку мы имеем дело с большими числами, вы можете проверить, есть ли у вас модуль в phpinfo).
Надеюсь, это поможет вам.
Это работает, даже если вы на 32-битном PHP:
Обратите внимание, что это не дает вам целые числа, а строки. Однако это хорошо работает во многих случаях, например, при создании URL-адресов для запросов REST.
Если вам нужны целые числа, требуется 64-битный PHP.
Затем вы можете повторно использовать приведенный выше код и использовать для (int):
Или вы можете использовать хорошие оль-лайнеры:
Php time с миллисекундами
(PHP 4, PHP 5, PHP 7, PHP 8)
time — Возвращает текущую метку системного времени Unix
Описание
Возвращает количество секунд, прошедших с начала эпохи Unix (1 января 1970 00:00:00 GMT) до текущего времени.
Список параметров
У этой функции нет параметров.
Возвращаемые значения
Возвращает текущую метку системного времени.
Примеры
Пример #1 Пример использования time()
Результатом выполнения данного примера будет что-то подобное:
Примечания
Смотрите также
User Contributed Notes 21 notes
The documentation should have this info. The function time() returns always timestamp that is timezone independent (=UTC).
Two quick approaches to getting the time elapsed in human readable form.
$nowtime = time ();
$oldtime = 1335939007 ;
/** Output:
time_elapsed_A: 6d 15h 48m 19s
time_elapsed_B: 6 days 15 hours 48 minutes and 19 seconds ago.
**/
?>
A time difference function that outputs the time passed in facebook’s style: 1 day ago, or 4 months ago. I took andrew dot macrobert at gmail dot com function and tweaked it a bit. On a strict enviroment it was throwing errors, plus I needed it to calculate the difference in time between a past date and a future date.
Argument order (begin date, end date) doesn’t matter.
I needed to convert between Unix timestamps and Windows/AD timestamps, so I wrote a pair of simple functions for it.
Below, a function to create TNG-style stardates, taking 2009 to start stardate 41000.0. In fact, the offset is trivial to adjust if you wish to begin from a different date.
Here’s a snippet of code that demonstrates the difference:
// Find the next second
$nextSecond = time () + 1 ;
// TIME: 1525735820 uTIME: 1525735820.997716
// TIME: 1525735820 uTIME: 1525735820.998137
// TIME: 1525735820 uTIME: 1525735820.998528
// TIME: 1525735820 uTIME: 1525735820.998914
// TIME: 1525735820 uTIME: 1525735820.999287
// TIME: 1525735820 uTIME: 1525735820.999657
// TIME: 1525735820 uTIME: 1525735821.000026 time() is behind
// TIME: 1525735820 uTIME: 1525735821.000367 time() is behind
// TIME: 1525735820 uTIME: 1525735821.000705 time() is behind
// TIME: 1525735820 uTIME: 1525735821.001042 time() is behind
// TIME: 1525735820 uTIME: 1525735821.001379 time() is behind
// TIME: 1525735821 uTIME: 1525735821.001718
// TIME: 1525735821 uTIME: 1525735821.002070
// TIME: 1525735821 uTIME: 1525735821.002425
// TIME: 1525735821 uTIME: 1525735821.002770
// TIME: 1525735821 uTIME: 1525735821.003109
// TIME: 1525735821 uTIME: 1525735821.003448
// TIME: 1525735821 uTIME: 1525735821.003787
// TIME: 1525735821 uTIME: 1525735821.004125
// TIME: 1525735821 uTIME: 1525735821.004480
Here’s a little tweak for those having trouble with cookies being set in the future or past (even after setting the date.timezone directive in php.ini or using the function):
Does anyone know if the year 2038 issue will be solved in PHP?
Lets imagine it’s year 2039 and the time() function will return negative numbers? This is not acceptable.
Using the DateTime interface is nice, but will these timestamp helper functions be removed or fixed?
If you want to create a «rounded» time stamp, for example, to the nearest 15 minutes use this as a reference:
= 60 * 15 // 60 seconds per minute * 15 minutes equals 900 seconds
//$round_numerator = 60 * 60 or to the nearest hour
//$round_numerator = 60 * 60 * 24 or to the nearest day
//If it was 12:40 this would return the timestamp for 12:45;
//3:04, 3:00; etc.
?>
I built this function to get the strtotime numbers for the beginning and ending of the month and return them as arrays in an object. Cheers.
The issue are highlighting is with the date() function, not with time(). the following code demonstrates this:
A better way to get a nice time-format (1 year ago, 2 months until) without all the trailing months, days, hours, minutes, seconds in the result is by using the DateTime format and using the date_diff function as they both does most of the heavy lifting for you
Function below as example
// Ex. (time now = November 23 2017)
getTimeInterval ( «2016-05-04 12:00:00» ); // Returns: 1 year ago
getTimeInterval ( «2017-12-24 12:00:00» ); // Returns: 1 month until
I did an article on floating point time you can download from my website. Roun movements is the radial ounion movement and there is a quantum ounion movement as well, this code will generate the data for http://www.chronolabs.org.au/bin/roun-time-article.pdf which is an article on floating point time, I have created the calendar system as well for this time. It is compatible with other time and other solar systems with different revolutions of the planets as well as different quantumy stuff.
Here’s one way to generate all intermediate dates (in mySQL format) between any 2 dates.
Get start and end dates from user input, you’d need to do the basic validations that :
— start and end dates are valid dates
— start date //start date 2001-02-23
$sm = 2 ;
$sd = 23 ;
$sy = 2001 ;
//end date 2001-03-14
$em = 3 ;
$ed = 14 ;
$ey = 2001 ;
A method return GMT time (gmttime):
elapsed time function with precision:
Here is a version for the difference code that displays «ago» code.
It does use some precision after the time difference is longer than a day. ( ie days are more than 60 * 60 * 24 hours long )
// Make the entered date into Unix timestamp from MySQL datetime field
// Calculate the difference in seconds betweeen
// the two timestamps