php new datetime format
Php new datetime format
Начиная с версии 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” в качестве первого параметра
Получаем количество недель в месяце
Следующий пример поможет вам получить количество недель в определенном месяце года.
Класс DateTime
(PHP 5 >= 5.2.0, PHP 7, PHP 8)
Введение
Обзор классов
Список изменений
Содержание
User Contributed Notes 26 notes
Set Timezone and formatting.
= time ();
$timeZone = new \ DateTimeZone ( ‘Asia/Tokyo’ );
DateTime supports microseconds since 5.2.2. This is mentioned in the documentation for the date function, but bears repeating here. You can create a DateTime with fractional seconds and retrieve that value using the ‘u’ format string.
// Instantiate a DateTime with microseconds.
$d = new DateTime ( ‘2011-01-01T15:03:01.012345Z’ );
There is a subtle difference between the following two statments which causes JavaScript’s Date object on iPhones to fail.
/**
On my local machine this results in:
Both of these strings are valid ISO8601 datetime strings, but the latter is not accepted by the constructor of JavaScript’s date object on iPhone. (Possibly other browsers as well)
*/
?>
Our solution was to create the following constant on our DateHelper object.
class DateHelper
<
/**
* An ISO8601 format string for PHP’s date functions that’s compatible with JavaScript’s Date’s constructor method
* Example: 2013-04-12T16:40:00-04:00
*
* PHP’s ISO8601 constant doesn’t add the colon to the timezone offset which is required for iPhone
**/
const ISO8601 = ‘Y-m-d\TH:i:sP’ ;
>
?>
Small but powerful extension to DateTime
class Blar_DateTime extends DateTime <
= new Blar_DateTime ( ‘1879-03-14’ );
Albert Einstein would now be 130 years old.
Albert Einstein would now be 130 Years, 10 Months, 10 Days old.
Albert Einstein was on 2010-10-10 131 years old.
Example displaying each time format:
$dateTime = new DateTime();
The above example will output:
At PHP 7.1 the DateTime constructor incorporates microseconds when constructed from the current time. Make your comparisons carefully, since two DateTime objects constructed one after another are now more likely to have different values.
This caused some confusion with a blog I was working on and just wanted to make other people aware of this. If you use createFromFormat to turn a date into a timestamp it will include the current time. For example:
if you’d like to print all the built-in formats,
This might be unexpected behavior:
#or use the interval
#$date1->add(new DateInterval(«P1M»));
#will produce 2017-10-1
#not 2017-09-30
A good way I did to work with millisecond is transforming the time in milliseconds.
function timeToMilliseconds($time) <
$dateTime = new DateTime($time);
If you have timezone information in the time string you construct the DateTime object with, you cannot add an extra timezone in the constructor. It will ignore the timezone information in the time string:
$date = new DateTime(«2010-07-05T06:00:00Z», new DateTimeZone(«Europe/Amsterdam»));
will create a DateTime object set to «2010-07-05 06:00:00+0200» (+2 being the TZ offset for Europe/Amsterdam)
To get this done, you will need to set the timezone separately:
$date = new DateTime(«2010-07-05T06:00:00Z»);
$date->setTimeZone(new DateTimeZone(«Europe/Amsterdam»);
This will create a DateTime object set to «2010-07-05 08:00:00+0200»
It isn’t obvious from the above, but you can insert a letter of the alphabet directly into the date string by escaping it with a backslash in the format string. Note that if you are using «double» speech marks around the format string, you will have to further escape each backslash with another backslash! If you are using ‘single’ speech marks around the format string, then you only need one backslash.
For instance, to create a string like «Y2014M01D29T1633», you *could* use string concatenation like so:
please note that using
setTimezone
setTimestamp
setDate
setTime
etc..
$original = new DateTime(«now»);
so a datetime object is mutable
(Editors note: PHP 5.5 adds DateTimeImmutable which does not modify the original object, instead creating a new instance.)
Create function to convert GregorianDate to JulianDayCount
Note that the ISO8601 constant will not correctly parse all possible ISO8601 compliant formats, as it does not support fractional seconds. If you need to be strictly compliant to that standard you will have to write your own format.
Bug report #51950 has unfortunately be closed as «not a bug» even though it’s a clear violation of the ISO8601 standard.
It seems like, due to changes in the DateTimeZone class in PHP 5.5, when creating a date and specifying the timezone as a a string like ‘EDT’, then getting the timezone from the date object and trying to use that to set the timezone on a date object you will have problems but never know it. Take the following code:
Be aware that DateTime may ignore fractional seconds for some formats, but not when using the ISO 8601 time format, as documented by this bug:
$dateTime = DateTime::createFromFormat(
DateTime::ISO8601,
‘2009-04-16T12:07:23.596Z’
);
// bool(false)
Be aware of this behaviour:
In my opinion, the former date should be adjusted to 2014/11/30, that is, the last day in the previous month.
Here is easiest way to find the days difference between two dates:
If you’re stuck on a PHP 5.1 system (unfortunately one of my clients is on a rather horrible webhost who claims they cannot upgrade php) you can use this as a quick workaround:
If you need DateTime::createFromFormat functionality in versions class DateClass extends DateTime <
<>
$regexpArray [ ‘Y’ ] = «(?P 19|20\d\d)» ;
$regexpArray [ ‘m’ ] = «(?P 06|1[012])» ;
$regexpArray [ ‘d’ ] = «(?P 02|[12]1|3[01])» ;
$regexpArray [ ‘-‘ ] = «[-]» ;
$regexpArray [ ‘.’ ] = «[\. /.]» ;
$regexpArray [ ‘:’ ] = «[:]» ;
$regexpArray [ ‘space’ ] = «[\s]» ;
$regexpArray [ ‘H’ ] = «(?P 09|18|23)» ;
$regexpArray [ ‘i’ ] = «(?P54)» ;
$regexpArray [ ‘s’ ] = «(?P29)» ;
DateTime::createFromFormat
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
Описание
Список параметров
Для вставки в format буквенного символа, вы должны экранировать его с помощью обратного слеша( \ ).
Начало эпохи Unix 1970-01-01 00:00:00 UTC.
Строка, представляющая время.
Если timezone не указан или null и datetime не содержит часовой пояс, то будет использован текущий часовой пояс.
Параметр timezone и текущий часовой пояс будут проигнорированы, если параметр datetime также содержит метку времени UNIX (то есть timestamp вида 946684800 ) или же указанный часовой пояс (то есть 2010-01-28T15:00:00+02:00 ).
Возвращаемые значения
Возвращает созданный экземпляр класса DateTime или false в случае возникновения ошибки.
Список изменений
Примеры
Пример #1 Пример использования DateTime::createFromFormat()
Результат выполнения данных примеров:
Пример #2 Хитрости при использовании DateTime::createFromFormat()
Результатом выполнения данного примера будет что-то подобное:
Пример #3 Формат строки с буквенными символами
Результатом выполнения данного примера будет что-то подобное:
Смотрите также
User Contributed Notes 27 notes
Be warned that DateTime object created without explicitely providing the time portion will have the current time set instead of 00:00:00.
Be aware:
If the day of the month is not provided, creating a DateTime object will produce different results depending on what the current day of the year is.
This is because the current system date will be used where values are not provided.
// on August 1st
printMonth ( «April» );
// outputs April
// on August 31st
printMonth ( «April» );
// outputs May
?>
In this case, each and every character on that string has to be escaped as shown below.
createFromFormat(‘U’) has a strange behaviour: it ignores the datetimezone and the resulting DateTime object will always have GMT+0000 timezone.
?>
The problem is microtime() and time() returning the timestamp in current timezone. Instead of using time you can use ‘now’ but to get a DateTimeObject with microseconds you have to write it this way to be sure to get the correct datetime:
Parsing RFC3339 strings can be very tricky when their are microseconds in the date string.
Since PHP 7 there is the undocumented constant DateTime::RFC3339_EXTENDED (value: Y-m-d\TH:i:s.vP), which can be used to output an RFC3339 string with microseconds:
Note: the difference between «v» and «u» is just 3 digits vs. 6 digits.
echo phpversion ();
// 7.2.7-1+ubuntu16.04.1+deb.sury.org+12019-01-102019-01-01
Reportedly, microtime() may return a timestamp number without a fractional part if the microseconds are exactly zero. I.e., «1463772747» instead of the expected «1463772747.000000». number_format() can create a correct string representation of the microsecond timestamp every time, which can be useful for creating DateTime objects when used with DateTime::createFromFormat():
If you’re here because you’re trying to create a date from a week number, you want to be using setISODate, as I discovered here:
date — Форматирует вывод системной даты/времени
Описание
Список параметров
Шаблон результирующей строки ( string ) с датой. См. параметры форматирования ниже. Также существует несколько предопределенных констант даты/времени, которые могут быть использованы вместо этих параметров. Например: DATE_RSS заменяет шаблон ‘D, d M Y H:i:s’.
Возвращаемые значения
Ошибки
Список изменений
Версия | Описание | ||
---|---|---|---|
5.1.0 | Допустимым диапазоном дат для временных меток обычно являются даты с 13 декабря 1901, 20:45:54 GMT по 19 января 2038, 03:14:07 GMT. (Они соответствуют минимальному и максимальному значению 32-битного целого числа со знаком). Однако для PHP версии ниже 5.1.0 в некоторых операционных системах (например, Windows) этот диапазон был ограничен датами 01-01-1970 до 19-01-2038. | ||
5.1.0 |
// вывод дня недели, например Wednesday echo date ( «l» ); // вывод даты в формате: Wednesday 15th of January 2003 05:51:38 AM Пример 2. Экранирование символов в функции date()
Пример 4. Форматирование с использованием date()
|