php сегодняшняя дата 3 дня
Дата и время в PHP
В распределенных системах, таких, как Интернет, время играет особую роль. Из-за незначительного расхождения системных часов игрок на рынке Forex может потерять десятки тысяч долларов в течение нескольких минут; система деловой разведки ошибется в составлении прогноза; серверы NNTP в процессе синхронизации потеряют важную информацию, нужную пользователю и т.д.
PHP-функции для работы с датой и временем
PHP содержит множество функций для работы с датой и временем. Наиболее употребимыми являются:
time() Возвращает текущее абсолютное время. Это число равно количеству секунд, которое прошло с полуночи 1 января 1970 года (с начала эпохи UNIX). getdate( ) Считывает информацию о дате и времени. Возвращает ассоциативный массив, содержащий информацию по заданному или по текущему (по умолчанию) времени. Массив содержит следующие элементы:
seconds | Секунды (0-59) |
minutes | Минуты (0-59) |
hours | Часы (0-23) |
mday | День месяца (1-31) |
wday | День недели (0-6), начиная с воскресенья |
mon | Месяц (1-12) |
year | Год |
yday | День года (0-365) |
weekday | Название дня недели (например, Friday) |
month | Название месяца (например, January) |
0 | Абсолютное время |
Пример 1
РЕЗУЛЬТАТ ПРИМЕРА 1:
seconds = 2
minutes = 49
hours = 0
mday = 5
wday = 5
mon = 11
year = 2021
yday = 308
weekday = Friday
month = November
0 = 1636062542
Сегодня: 5.11.2021
date() Форматирование даты и времени. Аргументы: строка формата и абсолютное время. Второй аргумент необязателен. Возвращает строку с заданной или текущей датой в указанном формате. Строка формата может содержать следующие коды:
Любая другая информация, включенная в строку формата, будет вставлена в возвращаемую строку. Если в строку формата нужно добавить символы, которые сами по себе являются кодами формата, то перед ними надо поставить обратную косую черту «\». Символы, которые становятся кодами формата при добавлении к ним обратной косой, нужно предварять двумя косыми. Например, если необходимо добавить в строку «n», то надо ввести «\\n», поскольку «\n» является символом новой строки.
Пример 2
РЕЗУЛЬТАТ ПРИМЕРА 2:
Сегодня 05.11.21 00:49
часы
минуты
секунды
месяц
день месяца
год
Пример 3
РЕЗУЛЬТАТ ПРИМЕРА 3:
22 January 1971, at 1.30 pm, Friday
Внимание! Дата может находиться в допустимом диапазоне, но остальные функции работы с датами не примут это значение. Так, нельзя использовать mktime() для годов до 1902, а также следует использовать ее осторожно для годов до 1970.
Пример 4
РЕЗУЛЬТАТ ПРИМЕРА 4:
Friday 05 November 2021 00:49
Сегодня Friday 05 November 2021 00:49:02
MSK
Функции даты и времени
Содержание
User Contributed Notes 25 notes
I ran into an issue using a function that loops through an array of dates where the keys to the array are the Unix timestamp for midnight for each date. The loop starts at the first timestamp, then incremented by adding 86400 seconds (ie. 60 x 60 x 24). However, Daylight Saving Time threw off the accuracy of this loop, since certain days have a duration other than 86400 seconds. I worked around it by adding a couple of lines to force the timestamp to midnight at each interval.
When debugging code that stores date/time values in a database, you may find yourself wanting to know the date/time that corresponds to a given unix timestamp, or the timestamp for a given date & time.
The following script will do the conversion either way. If you give it a numeric timestamp, it will display the corresponding date and time. If you give it a date and time (in almost any standard format), it will display the timestamp.
All conversions are done for your locale/time zone.
For those who are using pre MYSQL 4.1.1, you can use:
TO_DAYS([Date Value 1])-TO_DAYS([Date Value 2])
For the same result as:
DATEDIFF([Date Value 1],[Date Value 2])
This dateDiff() function can take in just about any timestamp, including UNIX timestamps and anything that is accepted by strtotime(). It returns an array with the ability to split the result a couple different ways. I built this function to suffice any datediff needs I had. Hope it helps others too.
I needed a function that determined the last Sunday of the month. Since it’s made for the website’s «next meeting» announcement, it goes based on the system clock; also, if today is between Sunday and the end of the month, it figures out the last Sunday of *next* month. lastsunday() takes no arguments and returns the date as a string in the form «January 26, 2003». I could probably have streamlined this quite a bit, but at least it’s transparent code. =)
/* The two functions calculate when the next meeting will
be, based on the assumption that the meeting will be on
the last Sunday of the month. */
I wanted to find all records in my database which match the current week (for a call-back function). I made up this function to find the start and end of the current week :
Not really elegant, but tells you, if your installed timezonedb is the most recent:
Someone may find this info of some use:
Rules for calculating a leap year:
1) If the year divides by 4, it is a leap year (1988, 1992, 1996 are leap years)
2) Unless it divides by 100, in which case it isn’t (1900 divides by 4, but was not a leap year)
3) Unless it divides by 400, in which case it is actually a leap year afterall (So 2000 was a leap year).
In practical terms, to work out the number of days in X years, multiply X by 365.2425, rounding DOWN to the last whole number, should give you the number of days.
The result will never be more than one whole day inaccurate, as opposed to multiplying by 365, which, over more years, will create a larger and larger deficit.
I needed to calculate the week number from a given date and vice versa, where the week starts with a Monday and the first week of a year may begin the year before, if the year begins in the middle of the week (Tue-Sun). This is the way weekly magazines calculate their issue numbers.
Here are two functions that do exactly that:
Hope somebody finds this useful.
Use the mySQL UNIX_TIMESTAMP() function in your SQL definition string. i.e.
$sql= «SELECT field1, field2, UNIX_TIMESTAMP(field3) as your_date
FROM your_table
WHERE field1 = ‘$value'»;
The query will return a temp table with coulms «field1» «Field2» «your_date»
The «your_date» will be formatted in a UNIX TIMESTAMP! Now you can use the PHP date() function to spew out nice date formats.
Hope this helps someone out there!
//function like dateDiff Microsoft
//not error in year Bissesto
Php сегодняшняя дата 3 дня
Описание string date ( string format [, int timestamp] )
Замечание: Для большинства систем допустимыми являются даты с 13 декабря 1901, 20:45:54 GMT по 19 января 2038, 03:14:07 GMT. (Эти даты соответствуют минимальному и максимальному значению 32-битового целого со знаком). Для Windows допустимы даты с 01-01-1970 по 19-01-2038.
Таблица 1. В параметре format распознаются следующие символы
Пример 1. Примеры использования функции date()
// вывод дня недели, например Wednesday echo date ( «l» ); // вывод даты в формате: Wednesday 15th of January 2003 05:51:38 AM Пример 2. Экранирование символов в функции date()
Пример 4. Форматирование с использованием date()
Php сегодняшняя дата 3 дняОписание string date ( string format [, int timestamp] )
Таблица 1. В параметре format распознаются следующие символы Пример 1. Примеры использования функции date()
|