- Секунды в минуты, часы, дни
- Результат в массиве
- Результат:
- Вывод строкой
- PHP microtime: How To Work With Different Time Units
- What Is microtime in PHP?
- Coding Examples
- – PHP microtime Function With Zero Arguments
- – Passing True to the PHP microtime Function
- Increase the Precision in Seconds
- – Coding Example
- Get PHP Timestamp Milliseconds
- – Coding Example
- Use PHP microtime To Get Unix Timestamp in Microseconds
- – Coding Example
- Format the Output
- – Coding Example
- PHP Timing Functions Returning Time in Seconds Only
- – Coding Example
- Conclusion
- microtime
- Parameters
- Return Values
- Examples
- See Also
- User Contributed Notes
Секунды в минуты, часы, дни
Две PHP функции для конвертирования секунд в дни, часы, минуты.
Результат в массиве
function secToArray($secs) < $res = array(); $res['days'] = floor($secs / 86400); $secs = $secs % 86400; $res['hours'] = floor($secs / 3600); $secs = $secs % 3600; $res['minutes'] = floor($secs / 60); $res['secs'] = $secs % 60; return $res; >$array = secToArray(167); print_r($array);
Результат:
Array( [days] => 0 [hours] => 0 [minutes] => 2 [secs] => 47 )
Вывод строкой
Понадобится функция для склонения числительных.
function num_word($value, $words, $show = true) < $num = $value % 100; if ($num >19) < $num = $num % 10; >$out = ($show) ? $value . ' ' : ''; switch ($num) < case 1: $out .= $words[0]; break; case 2: case 3: case 4: $out .= $words[1]; break; default: $out .= $words[2]; break; >return $out; > function secToStr($secs) < $res = ''; $days = floor($secs / 86400); $secs = $secs % 86400; $res .= num_word($days, array('день', 'дня', 'дней')) . ', '; $hours = floor($secs / 3600); $secs = $secs % 3600; $res .= num_word($hours, array('час', 'часа', 'часов')) . ', '; $minutes = floor($secs / 60); $secs = $secs % 60; $res .= num_word($minutes, array('минута', 'минуты', 'минут')) . ', '; $res .= num_word($secs, array('секунда', 'секунды', 'секунд')); return $res; >echo secToStr(167); // 0 дней, 0 часов, 2 минуты, 47 секунд echo secToStr(12345678); // 142 дня, 21 час, 21 минута, 18 секунд
PHP microtime: How To Work With Different Time Units
The PHP microtime function is the one that returns the current Unix timestamp with microseconds. And interestingly, you can use the said function to get time in other units as well, such as seconds. So, here you’ll see how the PHP microtime works, how you can use the same for converting time units, and which other function returns time in seconds.
Continue reading to fulfill the time requirements of your program effectively.
What Is microtime in PHP?
The PHP microtime is a built-in function that returns the current Unix timestamp in the “msec sec” format. Here, the “sec” represents the seconds, and the “msec” represents the microseconds after being converted into seconds. The given function accepts a single optional boolean argument “as_float.”
So, the result returned by the microtime in PHP can be read as “microseconds_as_seconds seconds.” Also, you can’t say that the microtime() function returns the current time in microseconds. Furthermore, if you pass “true” to the PHP microtime function, you’ll get the current time in seconds only.
Coding Examples
The following coding examples have been created to show you how to use the microtime function. Plus, you’ll be able to see the difference in the outputs based on the argument passed to the given function.
– PHP microtime Function With Zero Arguments
For example, you want to display the current time in the “microseconds_as_seconds seconds.” Here you’ll simply need to call the microtime() function without passing any arguments.
Please see the below one-liner code to get current time with microseconds:
// using the microtime function echo microtime(); // output: 0.28552700 1642373103 ?> |
– Passing True to the PHP microtime Function
For instance, you want to get the current time in seconds. You need to use the PHP microtime function by passing “true” as an argument.
Please have a look at this code block that compares the results obtained before and after passing “true” as an argument:
$msec_sec = microtime(); echo “Time as msec sec: $msec_sec ”; // output: Time as msec sec: 0.19812600 1642423688 $seconds = microtime(true); echo “Time in seconds: $seconds”; // output: Time in seconds: 1642423688.1981 ?> |
Increase the Precision in Seconds
Are you looking for a more precise time returned by the microtime(true) function? Well, it would be beneficial to note that the number of digits returned by the microtime(true) function depends on the value of the “precision” directive in the php.ini file. The said directive has its default value set to “14.” But if you want to have more digits, you can call the ini_set() function to set your desired number of digits.
– Coding Example
For instance, you want to set the precision to 16 digits instead of 14. Therefore, you’ll call the ini_set() function by passing the “precision” and “16” as arguments. Later, you’ll call the microtime(true) function to get the current time in seconds with more precision.
The coding instructions given here will assist you in increasing the precision:
// setting the precision to 16 ini_set(“precision”, 16); // executing the microtime(true) function echo microtime(true); // output: 1642439657.329814 ?> |
Get PHP Timestamp Milliseconds
Would you like to have PHP time in milliseconds? Indeed, you can get the time in milliseconds by using the result returned by the PHP microtime function. All that you’ll need to do is to multiply the output generated by the microtime(true) function by 1000. You shouldn’t doubt the process because it is a basic mathematics formula, and it is a fact that a second is 1000 times bigger than a millisecond.
– Coding Example
Suppose you have a program that requires time in milliseconds. So, you’ll simply execute the PHP microtime function by passing true as an argument. Consequently, you’ll get the current time in seconds, and then you’ll multiply the obtained seconds by 1000 to get PHP time in milliseconds.
The code block shared below will be helpful for you in understanding the entire process along with the accuracy of the result:
// multiply the result of microtime(true) by 1000 $milliseconds = microtime(true) * 1000; echo $milliseconds; // output: 1642423688198.1 ?> |
Use PHP microtime To Get Unix Timestamp in Microseconds
Is it possible to get the current Unix timestamp in microseconds? Undeniably, you can perform the necessary conversion to get time in microseconds, but the issue is the large value. As a microsecond is 1/1000000th part of a second, the resulting time value in microseconds will be long enough. And unfortunately, if you are using a 32-bit Operating System, you won’t get the desired time value.
However, if you have a 64-bit Operating System, you can multiply the output of the microtime(true) function by 1000000 to get the current time in microseconds.
– Coding Example
For instance, you have created a program that calls two functions with a timing difference of five seconds. Now, you want to see how many microseconds have elapsed between the two function calls. You’ll need to use the microtime(true) function and multiply the output of the same function by 1000000 at the time of calling the first function. Next, you’ll repeat the same process while executing the second function.
In the end, you’ll minus the second recorded time from the first one to get the elapsed time in microseconds as seen in the code fragment below:
// getting a part of a string $part = substr(“Welcome To Timing Functions”,5); // getting the time in microseconds $first = microtime(true) * 1000000; // setting the sleeping time to five seconds sleep(5); // replacing the word ‘Timing’ with ‘PHP’ in the substring str_replace(“Timing”,”PHP”,$part); // getting the time in microseconds $second = microtime(true) * 1000000; // calculating the time elapsed between the two function calls $difference = $second – $first; // printing a statement with elapsed microseconds echo “The word ‘Timing’ was replaced after $difference microseconds of getting the substring.”; ?> |
You will get the output that will look similar to this:
The word ‘Timing’ was replaced after 5015866 microseconds of getting the substring. |
Format the Output
Can you format the PHP microtime result in such a way that the “microseconds as seconds” follow the “seconds” without a dot and a space? Although there isn’t any special function to provide the time in the mentioned format, you can use the preg_replace() function to format the output generated by the microtime in PHP.
– Coding Example
Suppose you have a time requirement in your program that expects the same time value as the one produced by the PHP microtime function, but you aren’t allowed to add a dot and a space. You’ll need to use the preg_replace() function by passing “/(0).(d+) (d+)/” pattern and a replacement string “$3$1$2” along with the output of the PHP microtime function.
Also, please look at the code shown here to implement the above example:
// using the microtime() function $msec_sec = microtime(); // printing the time in “msec sec” format echo “$msec_sec ”; // using the preg_replace() function echo preg_replace(‘/(0).(d+) (d+)/’, ‘$3$1$2’, $msec_sec); ?> |
You will get a result similar to this after executing the above code:
0.18196800 1642435234 1642435234018196800 |
PHP Timing Functions Returning Time in Seconds Only
Unquestionably, the PHP microtime function gives quite satisfying results. But if you are concerned only about the current time in seconds, then the time() function can also be a good choice. The stated function returns the current time in seconds without considering the microseconds.
You can use it like this: time() .
– Coding Example
Imagine that you want to see how many seconds have passed since the Unix Epoch “January 1 1970 00:00:00 GMT.” Moreover, you want to compare the results of the microtime(true) and time() functions. So, there wouldn’t be a better idea than calling both of the functions at the same time to observe the difference in the obtained results.
You can copy and paste the given code snippet to get your current time in seconds by using the microtime(true) and time() functions:
// using the time function echo “Result of the time() function:” . time(); // using the microtime function echo “Result of the microtime(true) function:” . microtime(true); ?> |
Until you try out the above code, you can notice the difference in the outputs here:
Result of the time() function:1642432244 Result of the microtime(true) function:1642432244.2976 |
Conclusion
Summarizing the article, you have mastered the use of the PHP microtime function along with using the output of the same to generate different results. Now, it’s time to go through all the significant details to ensure that you don’t end up mixing any concepts:
- The PHP microtime function returns the current Unix timestamp in “microseconds_as_seconds seconds” format.
- The microtime(true) can be used to get the current Unix timestamp in seconds.
- You can increase the number of digits returned by the microtime(true) by increasing the value of the precision directive.
- You can multiply the output of the microtime(true) by 1000 to get the current time in milliseconds.
- You can get the current time in microseconds by multiplying the result of the microtime(true) by 1000000.
No doubt, different PHP programs have different timing requirements. But the tasks won’t be difficult to handle when you have already gained clarity with the relevant concepts.
microtime
microtime() returns the current Unix timestamp with microseconds. This function is only available on operating systems that support the gettimeofday() system call.
For performance measurements, using hrtime() is recommended.
Parameters
If used and set to true , microtime() will return a float instead of a string , as described in the return values section below.
Return Values
By default, microtime() returns a string in the form «msec sec», where sec is the number of seconds since the Unix epoch (0:00:00 January 1,1970 GMT), and msec measures microseconds that have elapsed since sec and is also expressed in seconds as a decimal fraction.
If as_float is set to true , then microtime() returns a float , which represents the current time in seconds since the Unix epoch accurate to the nearest microsecond.
Examples
Example #1 Timing script execution
// Sleep for a while
usleep ( 100 );
$time_end = microtime ( true );
$time = $time_end — $time_start ;
echo «Did nothing in $time seconds\n» ;
?>
Example #2 microtime() and REQUEST_TIME_FLOAT
// Randomize sleeping time
usleep ( mt_rand ( 100 , 10000 ));
?php
// REQUEST_TIME_FLOAT is available in the $_SERVER superglobal array.
// It contains the timestamp of the start of the request with microsecond precision.
$time = microtime ( true ) — $_SERVER [ «REQUEST_TIME_FLOAT» ];
echo «Did nothing in $time seconds\n» ;
?>
See Also
User Contributed Notes
- Date/Time Functions
- checkdate
- date_add
- date_create_from_format
- date_create_immutable_from_format
- date_create_immutable
- date_create
- date_date_set
- date_default_timezone_get
- date_default_timezone_set
- date_diff
- date_format
- date_get_last_errors
- date_interval_create_from_date_string
- date_interval_format
- date_isodate_set
- date_modify
- date_offset_get
- date_parse_from_format
- date_parse
- date_sub
- date_sun_info
- date_sunrise
- date_sunset
- date_time_set
- date_timestamp_get
- date_timestamp_set
- date_timezone_get
- date_timezone_set
- date
- getdate
- gettimeofday
- gmdate
- gmmktime
- gmstrftime
- idate
- localtime
- microtime
- mktime
- strftime
- strptime
- strtotime
- time
- timezone_abbreviations_list
- timezone_identifiers_list
- timezone_location_get
- timezone_name_from_abbr
- timezone_name_get
- timezone_offset_get
- timezone_open
- timezone_transitions_get
- timezone_version_get