Time counting in php

microtime

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

Для измерения производительности рекомендуется использовать hrtime() .

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

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

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

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

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

Примеры

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

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

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

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

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

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

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

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

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

  • time() — Возвращает текущую метку системного времени Unix
  • hrtime() — Получить системное время высокого разрешения

User Contributed Notes

  • Функции даты и времени
    • 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

    Источник

    The complete guide on working with dates and time in PHP

    As a developer, nearly every application you will work on requires the use of time in some way. You will need to keep a record of the time in which various activities occur, such as the time in which a record is created, updated, deleted, when a user logs in, etc.

    At some point, you’re going to have to collect, store, retrieve and display dates and times in different formats. You are also likely to do calculations involving time such as adding days to a day, subtracting a number of days from a date, comparing two days, etc.

    In this article, we will cover in detail working with dates and times in PHP.

    How computers count time

    Computers count time from an instant called Unix epoch, which occurred on January 1, 1970, at 00:00:00 UTC(Coordinated Universal Time). UTC is also known as GMT(Greenwich Meridian Time), which is the time at a longitude of 0°.

    Unix time elapses at the same rate as UTC. You can calculate the UTC date and time of any given instant since January 1, 1970, by counting the number of seconds since the Unix epoch, with the exception of leap seconds. Leap seconds are occasionally added to UTC to account for the slowing of the Earth’s rotation but are not added to Unix time.

    Unix Timestamp

    Unix timestamp is the number of seconds that have elapsed since January 1, 1970, at 00:00:00 UTC.

    Standard Dates Reporting

    Computers count time using Unix timestamp, calculating the number of seconds that have passed since Jan 1, 1970. However, this would be difficult and incredibly inefficient for humans. Thus, we work in terms of years, months, days, hours, minutes, and seconds.

    But this also comes with complexities because different regions and cultures have different ways of writing the date. For instance, dates in the United States are written starting with the month, then day, then the year. December 31, 2021, will be written as 12-31-2021. On the other hand, the same date will be written as 31-12-2021 in Europe and other regions.

    To standardize the date and help fix the communication mistakes, the International Organization for Standardization (ISO) introduced ISO8601. This standard specifies that all dates should be written in order of most-to-least-significant data. This means the format is the year, month, day, hour, minute, and second:

    In the example above, YYYY represents a four-digit year, and MM and DD are the two-digit month and day, starting with a zero if less than 10. After that, HH, MM, and SS represent the two-digit hours, minutes, and seconds, starting with a zero if less than 10.

    The above format eliminates the ambiguity in dates representation, where dates written as DD-MM-YYYY or MM-DD-YYYY can be misinterpreted if the day is a valid month number.

    Most databases use YYYY-MM-DD HH:MM:SS format to store date and time and YYYY-MM-DD to store date.

    Setting and getting timezone on your server

    Different regions of the world have different timezones. You can know which timezone your web server is set to with the following PHP function.

    To change to the timezone that will be used in your date and time functions in PHP, you do it with the function date_default_timezone_set($timezoneId), where $timezoneId is a string value.

    The above code sets the timezone to that of Nairobi, Kenya. You can get a list of all timezones on this link

    Unless all your website/app users are from the same region, it is always advisable to set your server time zone to UTC.

    Below is how you set timezone to UTC in PHP:

    For the date and time functions to pick and reflect the timezone specific time, you should always the function for setting the timezone at the top.

    Timestamp function: time()

    The function returns the current unix timestamp, ie. total number of seconds that have passed since January 1, 1970 at 00:00:00 UTC.

    PHP date() function

    The function returns a string formatted according to the given format string using the given integer timestamp.

    It takes the format below:

    Where $format is a string value and $timestamp an optional integer unix timestamp value.If $timestamp is not given, the function defaults to the value of time()

    Date function formatting options

    To convert/format a date in different formats using the date() function, you need to first convert that date into a Unix timestamp using the strtotime() function.

    Conversion of date/time to Unix timestamp

    The strtotime() function parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT).

    Example 2: Displaying current time in DateTime format

    Converting a date into different formats

    You can convert the date into as many formats as possible by just manipulating various letters in the table above to form within the date() function, enclosed in single or double-quotes.

    Adding and subtracting days or time to a DateTime

    The easiest way to add or subtract time to/from date in PHP is by concatenating a string specifying the duration of time you want to add or subtract, to date, inside the strtotime() function, preceded with the plus (+) or minus (-) symbol.

    Adding time to the current time

    Adding time to a DateTime

    Adding days, weeks, months and years to a date

    How to subtract 2 dates in PHP

    When you have two dates that you want to find their difference, PHP can help you find it.

    You just convert the two dates to unix timestamps, subtract the two timestamps and find the difference between the two dates in seconds.

    You then convert the time in seconds to the duration in which you want to measure the time in eg. hours, days, years, etc.

    If you use DateTime format(date and time in the date), use the floor() function to round down and avoid decimals in time difference like below.

    Comparison between 2 dates

    It is quite easy to compare two dates and know which is older than the other.

    If the two dates are exactly in the same format, you just compare them directly as below:

    If the two dates have different formats, you will first need to convert the two to the Unix timestamp, then compare them as below.

    Conclusion

    Nearly in all applications, you will ever work on as a developer, in whatever language you decide to use, you will have to work with dates and time in one way or another.

    In this article, we have covered working with dates in PHP. We have covered how computers count time, what Unix timestamp is, how to collect the current time, working with timezones, converting dates and time into multiple different formats, adding or subtracting time to or from a date, and dates comparison among other things.

    Источник

    Читайте также:  Context type in java
Оцените статью