php datetime to date
Php datetime to date
Начиная с версии 5.2 в PHP появился такой тип данных как DateTime. Попробуем в этой статье разобраться почему лучше использовать его вместо старых функций date() и time().
Функция time() возвращает текущее время в unix формате (timestamp).
Datetime()
Объект Datetime впервые был представлен в PHP версии 5.2, он содержит в себе множество вспомогательных объектов, для решения проблем, с которыми вам приходилось сталкиваться при использовании функций date() и time(). Также был представлен объект DateTimeZone, который управляет часовым поясом, объект DateInterval соответствует интервалу времени (например 2 дня) от настоящего момента, DatePeriod показывает разницу во времени между двумя разными датами. Основное преимущество использования DateTime перед старыми функциями заключается в том, что значения дат проще изменять. Если вы хотите получить значение времени и даты при помощи функции date(), то вы напишите следующее:
А вот пример для установки часового пояса:
Проблема возникает при необходимости изменить или сравнить две отметки времени, DateTime имеет методы modify() и diff() упрощающие задачу. Преимущества DateTime проявляются когда вы манипулируете значениями дат.
Сначала объект надо инициализировать
Вывод форматированной даты
Объект DateTime может работать также как и функция date, всего лишь необходимо вызвать метод format() указав формат возвращаемой строки.
Вывод отметки времени (timestamp)
Изменение времени
Изменение метки timestamp
Установка часового пояса
Полный список часовых поясов можно просмотреть на php.net.
Как добавить дни к значению даты
Для изменения значения даты в объекте DateTime можно использовать метод modify(). Он принимает в качестве параметра строковое значение дней, месяцев, года. Например, если хотите прибавить несколько дней, например 3 дня, один месяц и один год:
Сравнение двух дат
Код выше даст нам разницу двух дат в виде DateInterval.
Конвертация номера месяца и имени месяца
Довольно часто приходится получать имя месяца из его порядкового номера, для этого всего лишь нужно указать формат “F” в качестве первого параметра
Получаем количество недель в месяце
Следующий пример поможет вам получить количество недель в определенном месяце года.
Дата и время в 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 = 36
minutes = 55
hours = 2
mday = 18
wday = 6
mon = 9
year = 2021
yday = 260
weekday = Saturday
month = September
0 = 1631922936
Сегодня: 18.9.2021
date() Форматирование даты и времени. Аргументы: строка формата и абсолютное время. Второй аргумент необязателен. Возвращает строку с заданной или текущей датой в указанном формате. Строка формата может содержать следующие коды:
Любая другая информация, включенная в строку формата, будет вставлена в возвращаемую строку. Если в строку формата нужно добавить символы, которые сами по себе являются кодами формата, то перед ними надо поставить обратную косую черту «\». Символы, которые становятся кодами формата при добавлении к ним обратной косой, нужно предварять двумя косыми. Например, если необходимо добавить в строку «n», то надо ввести «\\n», поскольку «\n» является символом новой строки.
Пример 2
РЕЗУЛЬТАТ ПРИМЕРА 2:
Сегодня 18.09.21 02:55
часы
минуты
секунды
месяц
день месяца
год
Пример 3
РЕЗУЛЬТАТ ПРИМЕРА 3:
22 January 1971, at 1.30 pm, Friday
Внимание! Дата может находиться в допустимом диапазоне, но остальные функции работы с датами не примут это значение. Так, нельзя использовать mktime() для годов до 1902, а также следует использовать ее осторожно для годов до 1970.
Пример 4
РЕЗУЛЬТАТ ПРИМЕРА 4:
Saturday 18 September 2021 02:55
Сегодня Saturday 18 September 2021 02:55:36
MSK
Date/Time Functions
Table of Contents
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
strtotime
(PHP 4, PHP 5, PHP 7, PHP 8)
strtotime — Преобразует текстовое представление даты на английском языке в метку времени Unix
Описание
Каждый параметр функции использует временную метку по умолчанию, пока она не указана в этом параметре напрямую. Будьте внимательны и не используйте различные временные метки в параметрах, если на то нет прямой необходимости. Обратите внимание на date_default_timezone_get() для задания часового пояса различными способами.
Список параметров
Строка даты/времени. Объяснение корректных форматов дано в разделе Форматы даты и времени.
Временная метка, используемая в качестве базы для вычисления относительных дат.
Возвращаемые значения
Ошибки
Список изменений
Версия | Описание |
---|---|
8.0.0 | baseTimestamp теперь допускает значение null. |
Примеры
Пример #1 Пример использования функции strtotime()
Пример #2 Проверка ошибок
Примечания
Корректным диапазоном временных меток обычно являются даты с 13 декабря 1901 20:45:54 UTC по 19 января 2038 03:14:07 UTC. (Эти даты соответствуют минимальному и максимальному значению 32-битового знакового целого).
В 64-битных версиях PHP корректный диапазон временных меток фактически бесконечен, так как 64 битов хватит для представления приблизительно 293 миллиарда лет в обоих направлениях.
Чтобы избежать потенциальной неоднозначности, рекомендуется использовать даты в формате стандарта ISO 8601 ( YYYY-MM-DD ), либо пользоваться функцией DateTime::createFromFormat() там, где это возможно.
Смотрите также
User Contributed Notes 42 notes
I’ve had a little trouble with this function in the past because (as some people have pointed out) you can’t really set a locale for strtotime. If you’re American, you see 11/12/10 and think «12 November, 2010». If you’re Australian (or European), you think it’s 11 December, 2010. If you’re a sysadmin who reads in ISO, it looks like 10th December 2011.
The best way to compensate for this is by modifying your joining characters. Forward slash (/) signifies American M/D/Y formatting, a dash (-) signifies European D-M-Y and a period (.) signifies ISO Y.M.D.
The «+1 month» issue with strtotime
===================================
As noted in several blogs, strtotime() solves the «+1 month» («next month») issue on days that do not exist in the subsequent month differently than other implementations like for example MySQL.
A strtotime também funciona quando concatenamos strings,
UK dates (eg. 27/05/1990) won’t work with strotime, even with timezone properly set.
[red., derick]: What you instead should do is:
WARNING when using «next month», «last month», «+1 month», «-1 month» or any combination of +/-X months. It will give non-intuitive results on Jan 30th and 31st.
The way to get what people would generally be looking for when they say «next month» even on Jan 30 and Jan 31 is to use «first day of next month»:
strtotime() also returns time by year and weeknumber. (I use PHP 5.2.8, PHP 4 does not support it.) Queries can be in two forms:
— «yyyyWww», where yyyy is 4-digit year, W is literal and ww is 2-digit weeknumber. Returns timestamp for first day of week (for me Monday)
— «yyyy-Www-d», where yyyy is 4-digit year, W is literal, ww is 2-digit weeknumber and dd is day of week (1 for Monday, 7 for Sunday)
// Get timestamp of 32nd week in 2009.
strtotime ( ‘2009W32’ ); // returns timestamp for Mon, 03 Aug 2009 00:00:00
// Weeknumbers strtotime ( ‘2009W01’ ); // returns timestamp for Mon, 29 Dec 2008 00:00:00
// strtotime(‘2009W1’); // error! returns false
// See timestamp for Tuesday in 5th week of 2008
strtotime ( ‘2008-W05-2’ ); // returns timestamp for Tue, 29 Jan 2008 00:00:00
?>
Weeknumbers are (probably) computed according to ISO-8601 specification, so doing date(‘W’) on given timestamps should return passed weeknumber.
I tried using sams most popular example but got incorrect results.
Then I read the notes which said:
if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. ***If, however, the year is given in a two digit format and the separator is a dash (-), the date string is parsed as y-m-d.***
I run a theatre’s website. Obviously, I need to ensure shows that have already happened do not appear on web pages, so I use something on the lines of:
So strtotime($end_date) will always return the timestamp at 00:00 that day. If I instead used:
You are not restricted to the same date ranges when running PHP on a 64-bit machine. This is because you are using 64-bit integers instead of 32-bit integers (at least if your OS is smart enough to use 64-bit integers in a 64-bit OS)
The following code will produce difference output in 32 and 64 bit environments.
32-bit PHP: bool(false)
64-bit PHP: int(-30607689600)
This is true for php 5.2.* and 5.3
Also, note that the anything about the year 10000 is not supported. It appears to use only the last digit in the year field. As such, the year 10000 is interpretted as the year 2000; 10086 as 2006, 13867 as 2007, etc
For negative UNIX timestamps, strtotime seems to return the literal you passed in, or it may try to deduct the number of seconds from today’s date.
To work around this behaviour, it appears that the same behaviour as described in the DateTime classes applies:
Specifically this line here (in the EN manual):
Therefore strtotime(‘@-1000’) returns 1000 seconds before the epoch.
It took me a while to notice that strtotime starts searching from just after midnight of the first day of the month. So, if the month starts on the day you search for, the first day of the search is actually the next occurrence of the day.
In my case, when I look for first Tuesday of the current month, I need to include a check to see if the month starts on a Tuesday.
If you want to confront a date stored into mysql as a date field (not a datetime) and a date specified by a literal string, be sure to add «midnight» to the literal string, otherwise they won’t match:
//I.E.: today is 17/02/2011
echo strtotime ( ‘2011-01-01’ ); //1293836400
echo strtotime ( ‘first day of last month’ ); //1293888128 Note: it’s different from the previous one, since it computes also the seconds passed from midnight. So this one is always greater than simple ‘2011-01-01’
echo strtotime ( ‘midnight first day of last monty’ ); //1293836400 Note: it’s the same as ‘2011-01-01’
Apache claims this to be a ‘standard english format’ time. strtotime() feels otherwise.
I came up with this function to assist in parsing this peculiar format.
strtotime is awesome for converting dates.
in this example i will make an RSS date, an
ATOM date, then convert them to a human
readable m/d/Y dates.
[red.: This is a bug, and should be fixed. I have file an issue]
This comment apply to PHP5+
We can now do thing like this with strtotime:
= strtotime ( ‘Monday this week’ );
?>
However this works based on a week starting Sunday. I do not know if we can tweak this PHP behavior, anyone know?
strtotime() will convert a string WITHOUT a timezone indication as if the string is a time in the default timezone ( date_default_timezone_set() ). So converting a UTC time like ‘2018-12-06T09:04:55’ with strtotime() actually yields a wrong result. In this case use:
Adding a note to an already long page:
Try to be as specific as you can with the string you pass in. For example
Assuming today is July 31, the timestamp returned by strtotime(‘February’) will ultimately be seen as February 31 (non-existant obviously), which then is interpreted as March 3, thus giving a month name of March.
Interestingly, adding the year or the day will give you back the expected month.
strtotime() produces different output on 32 and 64 bit systems running PHP 5.3.3 (as mentioned previously). This affects the «zero date» («0000-00-00 00:00:00») as well as dates outside the traditional 32 date range.
In modern 64-bit systems (tested on mac) the old 1970 to 2038 date range limitations are gone.
strtotime(«0001-10-30») gives int(-62109540728)
strtotime(«6788-10-30») gives int(152067506400)