текущая метка времени php
Работа с датой и временем в PHP
Среди разнообразных задач программирования, различные манипуляции со значениями даты и времени встречаются достаточно часто. Редкая автоматизированная система, база данных может обойтись без сохранения информации о времени того или иного процесса. Помимо простейшего добавления даты в запись базы данных или отображения этой даты, встречаются множество задач вывода этих дат в различном виде, проверки соответствия текущего времени с заданным таймером, вычисление срока между двумя датами и многое другое.
Для удобства работы с датами каждый язык программирования имеет свои специальные типы данных для хранения значения даты и времени. Чаще всего это числовое значение, либо целое, либо с плавающей точкой.
В PHP работа с датой чаще всего сталкивается с UNIX TIMESTAMP. Здесь время хранится целым числом. Исчисление времени начинается с 1 января 1970 года. Поэтому, например, дата и время 11.12.2014 19:40:00, будет представлено числом 1418316000. Эта цифра показывает, сколько секунд прошло с нулевой даты 1 января 1970 года, названой Эпохой Unix.
Пример php-страницы, предоставляющий возможности преобразования данных представлен на сайте в разделе программ программой «Преобразование формата даты и времени». Здесь можно сформировать нужную дату в формат UNIX TIMESTAMP, а так же привести этот формат в стандартный, понятный человеку вид.
Получение текущего времени и даты в PHP
Для получения текущего времени сервера используется функция
которая как раз вернет значение в формате unix timestamp.
На первый взгляд не очень удобный формат для человека, но, как известно, чем проще представление данных, тем быстрее выполняется обработка этих значений компьютером. Кроме того, хранение числа в базе данных намного экономичнее, чем какой-либо специальный формат. Так же, PHP работает со временем одинаково и на Unix и на Windows платформе, что обеспечивает возможность использовать код на любой из этих платформ.
Преобразование формата даты и времени в PHP
Простейший механизм, позволяющий преобразовать числовое значение даты на более понятные значения, предоставляется функцией:
Она возвращает ассоциативный массив, содержащий информацию о дате. Если параметр timestamp не указан, будут возвращены сведения о текущем времени. Этот массив содержит следующие значения:
seconds | секунды (0-59) |
minutes | минуты (0-59) |
hours | часы (0-23) |
mday | день месяца (1-31) |
wday | день недели (0-6), начиная с воскресенья |
mon | месяц (1-12) |
year | год |
yday | день года (0-365) |
weekday | название дня недели (например, Monday) |
month | название месяца (например, January) |
0 | количество секунд, прошедших с начала Эпохи Unix |
Полученный массив, позволяет вывести значения нужном виде:
Так же для преобразования формата даты и времени можно воспользоваться функцией:
Формат задается следующими значениями:
Как видно из списка, с помощью этой функции можно получить очень много полезных данных о дате. Например:
Другие символы, входящие в шаблон, будут выведены в строке как есть. Если же потребуется ввести символ, который используется в функции как код формата, перед ними вставляется символ «\». Для значения «\n» (символ перехода на новую строку), следует указать «\\n». Таким образом, можно делать вывод целого сообщения, содержащего сведения о дате и времени:
Преобразование даты и времени в формат timestamp
Для обратного преобразования даты из стандартного формата в числовое значение timestamp применяется функция:
Функция mktime() возвращает значение времени Unix, соответствующую дате и времени, заданным аргументами. Например:
Следует внимательно относится к порядку аргументов функции: часы, минуты, секунды, месяц, день, год.
Кроме простого формирования значения даты в timestamp, функцию mktime() можно использовать для арифметически вычисления с датами. Для этого просто можно ввести необходимые аргументы. Например, если указать 14 месяц, то в итоговом значении, месяц будет 2-й, а значение года увеличится на единицу:
Аналогично можно поступать и с другими параметрами.
Проверка корректности даты в PHP
При работе с датами, особенно при формировании даты предложенной выше функцией mktime() необходимо учитывать корректность вводимой даты. Для этого в PHP используется функция:
Возвращает true если дата, заданная аргументами, является правильной; иначе возвращает false. Дата считается правильной, если:
— год в диапазоне от 1 до 32767;
— месяц в диапазоне от 1 до 12;
— день для заданного месяца с учетом високосного года указаны правильно.
mktime — Возвращает метку времени Unix для заданной даты
Описание
Аргументы могут быть опущены в порядке справа налево. В этом случае их значения по умолчанию равны соответствующим компонентам локальной даты/времени.
Примечания
Список параметров
Начиная с версии PHP 5.1.0 этот параметр более не рекомендуется к использованию. Вместо этого рекомендуется устанавливать соответствующую временную зону.
Возвращаемые значения
mktime() возвращает временную метку Unix в соответствии с переданными аргументами. Если были переданы некорректными аргументы, функция вернет FALSE (до версии PHP 5.1 возвращалась -1).
Ошибки
Список изменений
Примеры
Пример #1 Пример использования функции mktime()
// Устанавливаем используемую по умолчанию временную зону. Доступно, начиная с версии PHP 5.1
date_default_timezone_set ( ‘UTC’ );
Пример #2 mktime() example
Функцию mktime() удобно использовать для выполнения арифметических операций с датами, так как она вычисляет верные значения при некорректных аргументах. Например, в следующем примере каждая строка выведет «Jan-01-1998».
Пример #3 Последний день месяца
Примечания
До версии PHP 5.1.0, отрицательные временные метки не поддерживались ни под одной известной версией Windows, а также и некоторыми другими системами. Таким образом, диапазон корректных лет был ограничен датами от 1970 до 2038 г.
Смотрите также
Текущая метка времени php
(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.
I needed to convert between Unix timestamps and Windows/AD timestamps, so I wrote a pair of simple functions for it.
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):
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
Argument order (begin date, end date) doesn’t matter.
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.
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
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
(PHP 4, PHP 5, PHP 7, PHP 8)
date — Форматирует вывод системной даты/времени
Описание
Список параметров
Возвращаемые значения
Ошибки
Список изменений
Версия | Описание |
---|---|
8.0.0 | timestamp теперь допускает значение null. |
Примеры
Пример #1 Примеры использования функции date()
// установка часового пояса по умолчанию.
date_default_timezone_set ( ‘UTC’ );
// выведет примерно следующее: Monday
echo date ( «l» );
// выведет примерно следующее: Monday 8th of August 2005 03:12:46 PM
echo date ( ‘l jS \of F Y h:i:s A’ );
/* пример использования константы в качестве форматирующего параметра */
// выведет примерно следующее: Mon, 15 Aug 2005 15:12:46 UTC
echo date ( DATE_RFC822 );
Чтобы запретить распознавание символа как форматирующего, следует экранировать его с помощью обратного слеша. Если экранированный символ также является форматирующей последовательностью, то следует экранировать его повторно.
Пример #2 Экранирование символов в функции date()
Пример #3 Пример совместного использования функций date() и mktime()
Данный способ более надёжен, чем простое вычитание и прибавление секунд к метке времени, поскольку позволяет при необходимости гибко осуществить переход на летнее/зимнее время.
Пример #4 Форматирование с использованием date()
// Предположим, что текущей датой является 10 марта 2001, 5:16:18 вечера,
// и мы находимся в часовом поясе Mountain Standard Time (MST)
$today = date ( «F j, Y, g:i a» ); // March 10, 2001, 5:16 pm
$today = date ( «m.d.y» ); // 03.10.01
$today = date ( «j, n, Y» ); // 10, 3, 2001
$today = date ( «Ymd» ); // 20010310
$today = date ( ‘h-i-s, j-m-y, it is w Day’ ); // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date ( ‘\i\t \i\s \t\h\e jS \d\a\y.’ ); // it is the 10th day.
$today = date ( «D M j G:i:s T Y» ); // Sat Mar 10 17:16:18 MST 2001
$today = date ( ‘H:m:s \m \i\s\ \m\o\n\t\h’ ); // 17:03:18 m is month
$today = date ( «H:i:s» ); // 17:16:18
$today = date ( «Y-m-d H:i:s» ); // 2001-03-10 17:16:18 (формат MySQL DATETIME)
?>
Примечания
Смотрите также
User Contributed Notes 20 notes
Things to be aware of when using week numbers with years.
Conclusion:
if using ‘W’ for the week number use ‘o’ for the year.
In order to define leap year you must considre not only that year can be divide by 4!
The correct alghoritm is:
if (year is not divisible by 4) then (it is a common year)
else if (year is not divisible by 100) then (it is a leap year)
else if (year is not divisible by 400) then (it is a common year)
else (it is a leap year)
So the code should look like this:
For Microseconds, we can get by following:
echo date(‘Ymd His’.substr((string)microtime(), 1, 8).’ e’);
FYI: there’s a list of constants with predefined formats on the DateTime object, for example instead of outputting ISO 8601 dates with:
echo date ( ‘Y-m-d\TH:i:sO’ );
?>
You can use
echo date ( DateTime :: ISO8601 );
?>
instead, which is much easier to read.
this how you make an HTML5 tag correctly
It’s common for us to overthink the complexity of date/time calculations and underthink the power and flexibility of PHP’s built-in functions. Consider http://php.net/manual/en/function.date.php#108613
date() will format a time-zone agnostic timestamp according to the default timezone set with date_default_timezone_set(. ). Local time. If you want to output as UTC time use:
$tz = date_default_timezone_get ();
date_default_timezone_set ( ‘UTC’ );
For HTML5 datetime-local HTML input controls (http://www.w3.org/TR/html-markup/input.datetime-local.html) use format example: 1996-12-19T16:39:57
To generate this, escape the ‘T’, as shown below:
If timestamp is a string, date converts it to an integer in a possibly unexpected way:
The example below formats today’s date in three different ways:
The following function will return the date (on the Gregorian calendar) for Orthodox Easter (Pascha). Note that incorrect results will be returned for years less than 1601 or greater than 2399. This is because the Julian calendar (from which the Easter date is calculated) deviates from the Gregorian by one day for each century-year that is NOT a leap-year, i.e. the century is divisible by 4 but not by 10. (In the old Julian reckoning, EVERY 4th year was a leap-year.)
This algorithm was first proposed by the mathematician/physicist Gauss. Its complexity derives from the fact that the calculation is based on a combination of solar and lunar calendars.
At least in PHP 5.5.38 date(‘j.n.Y’, 2222222222) gives a result of 2.6.2040.
So date is not longer limited to the minimum and maximum values for a 32-bit signed integer as timestamp.
Prior to PHP 5.6.23, Relative Formats for the start of the week aligned with PHP’s (0=Sunday,6=Saturday). Since 5.6.23, Relative Formats for the start of the week align with ISO-8601 (1=Monday,7=Sunday). (http://php.net/manual/en/datetime.formats.relative.php)
This can produce different, and seemingly incorrect, results depending on your PHP version and your choice of ‘w’ or ‘N’ for the Numeric representation of the day of the week:
Prior to PHP 5.6.23, this results in:
Today is Sun 2 Oct 2016, day 0 of this week. Day 1 of next week is 10 Oct 2016
Today is Sun 2 Oct 2016, day 7 of this week. Day 1 of next week is 10 Oct 2016
Since PHP 5.6.23, this results in:
Today is Sun 2 Oct 2016, day 0 of this week. Day 1 of next week is 03 Oct 2016
Today is Sun 2 Oct 2016, day 7 of this week. Day 1 of next week is 03 Oct 2016
I’ve tested it pretty strenuously but date arithmetic is complicated and there’s always the possibility I missed something, so please feel free to check my math.
The function could certainly be made much more powerful, to allow you to set different days to be ignored (e.g. «skip all Fridays and Saturdays but include Sundays») or to set up dates that should always be skipped (e.g. «skip July 4th in any year, skip the first Monday in September in any year»). But that’s a project for another time.
$start = strtotime ( «1 January 2010» );
$end = strtotime ( «13 December 2010» );
// Add as many holidays as desired.
$holidays = array();
$holidays [] = «4 July 2010» ; // Falls on a Sunday; doesn’t affect count
$holidays [] = «6 September 2010» ; // Falls on a Monday; reduces count by one
?>
Or, if you just want to know how many work days there are in any given year, here’s a quick function for that one: