- PHP Date/Time Functions
- Installation
- Runtime Configuration
- PHP Date/Time Functions
- PHP Predefined Date/Time Constants
- Функции временных меток PHP
- Получение текущей временной метки в PHP
- time()
- StrToTime ()
- mktime()
- microtime()
- Microseconds in PHP Date / Time Displays
- microtime
- Parameters
- Return Values
- Examples
- See Also
- User Contributed Notes
PHP Date/Time Functions
The date/time functions allow you to get the date and time from the server where your PHP script runs. You can then use the date/time functions to format the date and time in several ways.
Note: These functions depend on the locale settings of your server. Remember to take daylight saving time and leap years into consideration when working with these functions.
Installation
The PHP date/time functions are part of the PHP core. No installation is required to use these functions.
Runtime Configuration
The behavior of these functions is affected by settings in php.ini:
Name | Description | Default | PHP Version |
---|---|---|---|
date.timezone | The default timezone (used by all date/time functions) | «» | PHP 5.1 |
date.default_latitude | The default latitude (used by date_sunrise() and date_sunset()) | «31.7667» | PHP 5.0 |
date.default_longitude | The default longitude (used by date_sunrise() and date_sunset()) | «35.2333» | PHP 5.0 |
date.sunrise_zenith | The default sunrise zenith (used by date_sunrise() and date_sunset()) | «90.83» | PHP 5.0 |
date.sunset_zenith | The default sunset zenith (used by date_sunrise() and date_sunset()) | «90.83» | PHP 5.0 |
PHP Date/Time Functions
Function | Description |
---|---|
checkdate() | Validates a Gregorian date |
date_add() | Adds days, months, years, hours, minutes, and seconds to a date |
date_create_from_format() | Returns a new DateTime object formatted according to a specified format |
date_create() | Returns a new DateTime object |
date_date_set() | Sets a new date |
date_default_timezone_get() | Returns the default timezone used by all date/time functions |
date_default_timezone_set() | Sets the default timezone used by all date/time functions |
date_diff() | Returns the difference between two dates |
date_format() | Returns a date formatted according to a specified format |
date_get_last_errors() | Returns the warnings/errors found in a date string |
date_interval_create_from_date_string() | Sets up a DateInterval from the relative parts of the string |
date_interval_format() | Formats the interval |
date_isodate_set() | Sets the ISO date |
date_modify() | Modifies the timestamp |
date_offset_get() | Returns the timezone offset |
date_parse_from_format() | Returns an associative array with detailed info about a specified date, according to a specified format |
date_parse() | Returns an associative array with detailed info about a specified date |
date_sub() | Subtracts days, months, years, hours, minutes, and seconds from a date |
date_sun_info() | Returns an array containing info about sunset/sunrise and twilight begin/end, for a specified day and location |
date_sunrise() | Returns the sunrise time for a specified day and location |
date_sunset() | Returns the sunset time for a specified day and location |
date_time_set() | Sets the time |
date_timestamp_get() | Returns the Unix timestamp |
date_timestamp_set() | Sets the date and time based on a Unix timestamp |
date_timezone_get() | Returns the time zone of the given DateTime object |
date_timezone_set() | Sets the time zone for the DateTime object |
date() | Formats a local date and time |
getdate() | Returns date/time information of a timestamp or the current local date/time |
gettimeofday() | Returns the current time |
gmdate() | Formats a GMT/UTC date and time |
gmmktime() | Returns the Unix timestamp for a GMT date |
gmstrftime() | Formats a GMT/UTC date and time according to locale settings |
idate() | Formats a local time/date as integer |
localtime() | Returns the local time |
microtime() | Returns the current Unix timestamp with microseconds |
mktime() | Returns the Unix timestamp for a date |
strftime() | Formats a local time and/or date according to locale settings |
strptime() | Parses a time/date generated with strftime() |
strtotime() | Parses an English textual datetime into a Unix timestamp |
time() | Returns the current time as a Unix timestamp |
timezone_abbreviations_list() | Returns an associative array containing dst, offset, and the timezone name |
timezone_identifiers_list() | Returns an indexed array with all timezone identifiers |
timezone_location_get() | Returns location information for a specified timezone |
timezone_name_from_ abbr() | Returns the timezone name from abbreviation |
timezone_name_get() | Returns the name of the timezone |
timezone_offset_get() | Returns the timezone offset from GMT |
timezone_open() | Creates new DateTimeZone object |
timezone_transitions_get() | Returns all transitions for the timezone |
timezone_version_get() | Returns the version of the timezonedb |
PHP Predefined Date/Time Constants
Constant | Description |
---|---|
DATE_ATOM | Atom (example: 2019-01-18T14:13:03+00:00) |
DATE_COOKIE | HTTP Cookies (example: Fri, 18 Jan 2019 14:13:03 UTC) |
DATE_ISO8601 | ISO-8601 (example: 2019-01-18T14:13:03+0000) |
DATE_RFC822 | RFC 822 (example: Fri, 18 Jan 2019 14:13:03 +0000) |
DATE_RFC850 | RFC 850 (example: Friday, 18-Jan-19 14:13:03 UTC) |
DATE_RFC1036 | RFC 1036 (example: Friday, 18-Jan-19 14:13:03 +0000) |
DATE_RFC1123 | RFC 1123 (example: Fri, 18 Jan 2019 14:13:03 +0000) |
DATE_RFC2822 | RFC 2822 (example: Fri, 18 Jan 2019 14:13:03 +0000) |
DATE_RFC3339 | Same as DATE_ATOM (since PHP 5.1.3) |
DATE_RFC3339_EXTENDED | RFC3339 Extended format (since PHP 7.0.0) (example: 2019-01-18T16:34:01.000+00:00) |
DATE_RSS | RSS (Fri, 18 Jan 2019 14:13:03 +0000) |
DATE_W3C | World Wide Web Consortium (example: 2019-01-18T14:13:03+00:00) |
SUNFUNCS_RET_TIMESTAMP | Timestamp (since PHP 5.1.2) |
SUNFUNCS_RET_STRING | Hours:minutes (example: 09:41) (since PHP 5.1.2) |
SUNFUNCS_RET_DOUBLE | Hours as a floating point number (example: 9.75) (since PHP 5.1.2) |
Функции временных меток PHP
PHP предоставляет несколько функций для выполнения операций с временными данными. В этой статье мы рассмотрим функции временных меток PHP.
Временная метка — это значение, представленное в секундах, которое рассчитывается с начала эпохи UNIX, 1 января 1970 года.
В этой статье мы рассмотрим, как с помощью PHP-функций даты и времени, связанных с временными метками:
Получение текущей временной метки в PHP
Текущее значение временной метки можно получить тремя способами.
time()
Это функция PHP для получения текущего значения временной метки. Она не принимает никаких аргументов. Пример использования:
StrToTime ()
Функция предназначена для получения метки времени из заданной строки, представляющей собой значение даты. Например, “Tuesday last week”, “+1 week”, “21 November 2008” и т. д.
Для получения текущей временной метки нужно передать функции значение “now”:
При вызове strtotime() с переданными некорректными данными, которые не поддерживаются PHP, а функция вернет значение false.
mktime()
Используется для получения метки времени UNIX. Функция принимает набор параметров, обозначающих час, минуты, секунды, месяц, день и год. А также дополнительный флаг, представляющий состояние летнего времени.
Чтобы получить текущую временную метку, в качестве параметра функции передается date() с соответствующими значениями. Например:
microtime()
Описанные выше функции PHP возвращают только десятизначное значение. Но microtime() возвращает количество секунд и микросекунд, прошедших с начала эпохи UNIX.
Функция не требует обязательных параметров. Есть необязательный параметр $get_as_float. Он принимает логические значения. Если передать TRUE, то microtime() вернет значение с плавающей запятой. Если FALSEв формате «микросекунды и секунды».
Microseconds in PHP Date / Time Displays
The suffix .577700 is the microseconds portion of the result from microtime(). PHP date() can digest the pattern Y-m-d H:i:s.u but it expects an integer as input, so it cannot render the .u portion of the pattern as anything other than .000000
The PHP man page for date() refers us to this if we want to format microseconds.
http://php.net/manual/en/datetime.format.php
Can someone please help me connect the dots from the value of microtime(TRUE) to an output string that includes the microseconds? Thanks and regards, ~Ray
THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
GET A PERSONALIZED SOLUTION
THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
GET A PERSONALIZED SOLUTION
Thanks, Chris. Here is what I had.
error_reporting(E_ALL); // A FUNCTION TO RETURN ISO-8601 FORMATTED DATE WITH MICROSECONDS APPENDED function date_usec($microtime=FALSE, $pat='Y-m-d H:i:s') // http://php.net/manual/en/function.microtime.php if (!$microtime) $microtime = microtime(TRUE); $dat = date($pat, $microtime); $usc = '000000'; $str = (string)$microtime; if (strpos($str, '.')) $usc = str_pad( end(explode('.', $str)), 6, '0', STR_PAD_RIGHT); return $dat . '.' . $usc; > // SET TIME ZONE date_default_timezone_set('America/Chicago'); // MICROSECONDS IN FLOAT $now = microtime(TRUE); // TEST THE FUNCTION echo '';
echo PHP_EOL . date_usec($now); usleep (101); echo PHP_EOL . date_usec(); usleep (101); echo PHP_EOL . date_usec( time() );
This seems like an inordinately large amount of code when the intuitive thing would be for PHP to modify the date() function to accept a float value instead of truncating it to an integer. With the decimal portion of the float, it would seem to be easy to produce the "u" portion of the pattern.
Also, if you want a DateTime object:
list($ts,$ms) = explode(".",microtime(true ));
$dt = new DateTime(date("Y-m-d H:i:s.",$ts).$ms);
echo $dt->format("Y-m-d H:i:s.u");
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
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