Datetime object php
Datetime object php
Начиная с версии 5.2 в PHP появился такой тип данных как DateTime. Попробуем в этой статье разобраться почему лучше использовать его вместо старых функций date() и time().
Функция date() используется для строкового отображения даты/времени. Функция принимает два параметра, 1-ый — формат возвращаемой строки, а второй — само значение даты. По умолчанию второй параметр принимает значение текущего момента времени, либо можно указать отметку времени в unix формате (timestamp).
Функция time() возвращает текущее время в unix формате (timestamp).
Datetime()
Объект Datetime впервые был представлен в PHP версии 5.2, он содержит в себе множество вспомогательных объектов, для решения проблем, с которыми вам приходилось сталкиваться при использовании функций date() и time(). Также был представлен объект DateTimeZone, который управляет часовым поясом, объект DateInterval соответствует интервалу времени (например 2 дня) от настоящего момента, DatePeriod показывает разницу во времени между двумя разными датами. Основное преимущество использования DateTime перед старыми функциями заключается в том, что значения дат проще изменять. Если вы хотите получить значение времени и даты при помощи функции date(), то вы напишите следующее:
А вот пример для установки часового пояса:
Проблема возникает при необходимости изменить или сравнить две отметки времени, DateTime имеет методы modify() и diff() упрощающие задачу. Преимущества DateTime проявляются когда вы манипулируете значениями дат.
Сначала объект надо инициализировать
Конструктор этого класса принимает два параметра. Первый — значение времени, вы можете использовать строку в формате функции date, время в формате Unix, интервал или период. Второй параметр — часовой пояс.
Вывод форматированной даты
Объект DateTime может работать также как и функция date, всего лишь необходимо вызвать метод format() указав формат возвращаемой строки.
Вывод отметки времени (timestamp)
Для вывода отметки времени в формате Unix существует метод getTimestamp() .
Изменение времени
Для изменения значения времени существует метод setTime() .
Изменение метки timestamp
Для этого придуман метод setTimestamp() .
Установка часового пояса
Второй параметр при создании объекта — DateTimeZone, он позволяет назначить часовой пояс нашему объекту. Это означает, что мы сможем легко сравнивать два значения времени из разных часовых поясов и получать корректную разницу.
Также для установки этого значения существует метод setTimezone() .
Полный список часовых поясов можно просмотреть на php.net.
Как добавить дни к значению даты
Для изменения значения даты в объекте DateTime можно использовать метод modify(). Он принимает в качестве параметра строковое значение дней, месяцев, года. Например, если хотите прибавить несколько дней, например 3 дня, один месяц и один год:
Сравнение двух дат
Код выше даст нам разницу двух дат в виде DateInterval.
Конвертация номера месяца и имени месяца
Довольно часто приходится получать имя месяца из его порядкового номера, для этого всего лишь нужно указать формат “F” в качестве первого параметра
При использовании класса DateTime можно применить метод format() .
Получаем количество недель в месяце
Следующий пример поможет вам получить количество недель в определенном месяце года.
Master PHP DateTime
It’s a common task to work with date and time as a web developer. If you are still using functions like strtotime and date to work with date and time, you are missing out.
PHP provides a dedicated class DateTime for dealing with date and time. Most of people have been ignoring it, despite it has been available since PHP 5.2.
A couple of reasons why you should use DateTime over strtotime and date:
- DateTime is able to process more date string formats comparing to strtotime.
- Working with object is just easier than arbitrary functions. E.g. Comparison of two date is direct with DateTime. Whereas with strtotime, we need to convert dates to timestamps and compare them.
- DateTime‘s object-oriented interface encapsulates a lot of back-end logic and provides a clean interface for us to use.
Table Of Content
Instantiation
Instantiating an DateTime object is no different from instantiating any other objects in PHP. We instantiate an DateTime object via its constructor.
When no parameter is supplied, an DateTime object with current timestamp and the default timezone will be created. The default timezone is normally configured in php.ini file.
For example, to create a «now» DateTime object:
Optionally we can supply a string, which represents a valid date and time, as the first parameter of the DateTime‘s constructor. The default timezone will still be used since it is not specified.
A few examples of creating DateTime objects with valid time string:
The second parameter of the DateTime‘s constructor allows us to specify a timezone. This parameter accepts a DateTimeZone object only.
For example, to create a DateTime object with Singapore timezone:
Of cause, we can also create a DateTime object with traditional date string:
Format
We will always want a specific format depends on the system we are building.
Formatting a DateTime object to get a custom string representation is straightforward. It’s done via DateTime‘s format() method.
DateTime::format() accepts a single string parameter. This string should contain options listed at PHP official page.
For example, to get a yyyy-dd-mm format outputted by DateTime, we can do:
We can create any desired format, because the format parameter provides all the possible options.
A few more examples:
Comparison
When working with date string, we need to convert them to timestamp using strtotime in order to compare their value.
DateTime objects work with comparison operators out of box. We can directly compare two DateTime objects just like two numeric values.
A few examples of comparing two DateTime objects:
Sometimes, a Boolean value of comparing two dates objects is not sufficient. We may want to know the exact difference between two dates.
DateTime::diff is a function for getting the difference between two DateTime objects. This function returns a DateInterval object, which we can use to retrieve any desired interval format through its function DateInterval::format.
For example, to get days difference between $today and $yesterday, we can do:
There are a number of interval properties in DateInterval class, you can check them out at PHP official site.
Manipulation
Though in reality, we can never manipulate time, with DateTime, we can actually do that. This means DateTime objects are mutable.
Addition
Adding to an existing DateTime is done through function DateTime::add. DateTime::add accepts a single DateInterval object parameter.
Let’s demonstrate how addition works in a simple example:
Most of the code above is easy to understand. The only tricky part may be creating a DateInterval object. DateInterval‘s constructor accepts a string that contains a valid interval specification.
An intercept of explanation for interval specification from PHP official site:
The format starts with the letter P, for «period.» Each duration period is represented by an integer value followed by a period designator. If the duration contains time elements, that portion of the specification is preceded by the letter T.
In our code above, we have used ‘P2D’, which standards for two days, to create a DateInterval object.
Subtraction
Similar to DateTime::add, subtraction is done through function DateTime::sub. DateTime::sub function accepts a DateInterval object just like DateTime::add function.
To subtract two days from $today, we can do:
Modification
Modification of a DateTime object is also possible with DateTime::modify function.
Comparing to DateTime::add function and DateTime::sub function, DateTime::modify function takes a different type of parameter to do the job. It accepts a date/time string. There is a wide range of support for the date/time string, you can check them out in details at PHP official site.
To subtract two days from $today with DateTime::modify function, we can do:
You have learned how to create, format, compare and even manipulate DateTime object so far. With what you have learned, you should be able to replace functions such as strtotime and date with DateTime object confidently in your future projects.
Sooner or later, you will be using DateTime objects for doing the same tasks over and over again. That has been the case for most of developers.
Tasks such as calculating someone’s age based on his birthday or testing if a date is tomorrow are pretty common. PHP developers decided to consolidate various tasks that involving DateTime into some generic packages. Hence a number of packages related to DateTime were developed over the years.
Some outstanding ones are recommended by the community. We will encourage you to check out two of them as shown below. They are notably good. Because they not only provide a lot of help functions for dealing with DateTime, but also they are well documented.
- Carbon: A simple PHP API extension for DateTime. (Documentation link)
- Chronos: It provides a zero-dependency collection of extensions to the DateTime object. (Documentation link)
Glossary
Links
Links to mentioned resources.
Characters recognized when using DateTime::format function:
Date interval specification:
Supported date/time string in PHP:
Carbon: A simple PHP API extension for DateTime:
Chronos: It provides a zero-dependency collection of extensions to the DateTime object.
Работа с датой и временем в PHP в ООП стиле. Часть 1
Перед web-разработчиками часто возникают задачи, в которых они должны работать с датой и временем. Если вы все еще используете PHP функции, такие как strtotime и date для работы с датой и временем в PHP, то вы многое упускаете.
PHP предоставляет специализированный класс DateTime для работы с датой и временем. Однако, многие игнорируют его использование, несмотря на то, что он доступен в PHP начиная с версии 5.2.
Вот несколько причин, почему предпочтительнее использовать класс DateTime вместо strtotime и date:
- Класс DateTime может работать с большим числом форматов даты и времени по сравнению с strtotime.
- Работать с объектами легче, чем с функциями. Даты, являющиеся объектами класса DateTime можно сравнивать напрямую, как обычные числа. Тогда как для сравнения двух дат с помощью функции strtotimе нам необходимо сначала преобразовать их во временные метки и только затем сравнить.
- Объектно-ориентированный интерфейс DateTime скрывает много внутренней логики работы с датой и обеспечивает понятный и однозначный интерфейс.
Создание объекта класса DateTime.
Создание объекта класса DateTime ничем не отличается от создания экземпляра какого-либо другого класса в PHP.
Если в конструктор класса DateTime не передавать параметр, то будет создан объект с текущей временной меткой и временной зоной по умолчанию. Временная зона в PHP, как правило, настраивается в файле php.ini. Вот так создается объект DateTime с текущим временем.
$now = new DateTime();
При необходимости мы можем передать в конструктор класса DateTime строку, представляющую собой правильную дату и время. В качестве временной зоны будет использована та, что установлена по умолчанию.
Несколько примеров создания объекта DateTime с передачей в конструктор строки, содержащей время.
$yesterday = new DateTime(‘yesterday’); // вчера
$twoDaysLater = new DateTime(‘+ 2 days’); // на 2 дня вперед
$oneWeekEarly = new DateTime(‘- 1 week’); // минус одна неделя
Второй параметр конструктора класса DateTime позволяет определить временную зону. Этот параметр имеет тип DateTimeZone.
Например, чтобы создать объект класса DateTime с временной зоной Москвы надо сделать следующее:
$yesterdayInMoscow = new DateTime(‘yesterday’, new DateTimeZone(‘Moscow’));
Конечно, мы также можем создать объект DateTime как обычно, с помощью строки.
$dateTime = new DateTime(‘2015-01-01 12:30:12’);
Формат
В зависимости от системы, которую мы собираемся проектировать, нам могут понадобится различные форматы даты и времени. Форматирование объекта DateTime в формат необходимый в конкретном проекте достаточно просто делается через метод DateTime::format().
Метод DateTime::format() принимает в качестве параметра строку. Эта строка может включать плейсхолдеры, перечисленные на странице официальной документации PHP.
Например, чтобы получить подобный формат YYYY-dd-mm, где Y – год, d – день, m – месяц необходимо сделать следующее:
$now = new DateTime();
$now = $now->format(‘Y-m-d’);
Мы можем создать любой желаемый формат даты. Вот несколько дополнительных опций:
print_r($now->format(‘jS F Y’));
print_r($now->format(‘ga jS M Y’));
print_r($now->format(‘Y/m/d s:i:H’));
Сравнение дат и времени
Для того, чтобы сравнить две даты с помощью встроенной в PHP функции strtotime, нам сначала нужно преобразовать строковое содержимое этих дат в их эквиваленты временных меток.
В отличие же, от данной функции, объект DateTime предоставляет возможность сравнивать два объекта DateTime как два обычных числа. Вот несколько примеров:
$today = new DateTime(‘today’);
$yesterday = new DateTime(‘yesterday’);
var_dump($today > $yesterday); // bool(true)
var_dump($today
Но бывают случаи, когда логическое значение от сравнения двух дат недостаточно. Например, нам нужно знать, точную разницу между двумя датами. И DateTime::diff() является тем методом, который поможет нам узнать разницу между двумя объектами DateTime. Этот метод возвращает объект класса DateInterval, который может быть использован для получения интервала, в любом требуемом нами формате посредством метода DateInterval::format.
Например, для получения количества дней между сегодняшней датой и вчерашней датой, мы можем сделать следующее:
$interval = $today->diff($yesterday);
echo $interval->format(‘%d день назад’) // 1 день назад
Со всем разнообразием свойств класса DateInterval вы можете ознакомиться на официальном сайте PHP.
На этом все, и в следующей статье мы продолжим изучать классы для работы с датой и временем в PHP.
Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!
Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.
Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления
Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.
Порекомендуйте эту статью друзьям:
Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):
Она выглядит вот так:
Комментарии ( 3 ):
Всем привет извините что пишу здесь но е могли бы подсказать хотел бы узнать как сделать так что бы ретрансляцию для моего сайта хочу чтобы например телеканал тнт транслировалась прямо с моего сайта а не сервера тнт.. Вот этот сайт введет трансляцию мачт тв с своего сервера http://fifa.beta.tj/schedule
Уточните, пожалуйста, вы хотите чтобы, когда пользователь заходил к Вам на сайт, то он мог бы смотреть передачу на вашем сайте?
ну вот например есть код видео трансляции (ТНТ) для вставки для других сайтов . и когда я вставлю этот код у посетителей расходуется трафик из сервера тнт, Я хочу чтобы расходовалось из моего сервера
Для добавления комментариев надо войти в систему.
Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.
Copyright © 2010-2020 Русаков Михаил Юрьевич. Все права защищены.
Get to Know Functions and Constants Used for PHP DateTime Format
PHP date and time can be formatted in multiple different ways in your PHP code. You might need a Unix timestamp or GMT date, a DateTime object or an ISO date. Therefore, it is important to learn functions that are applied to manipulate PHP DateTime format.
PHP date formatting is not that hard, but you still have to have specific knowledge and expertise. Fetching the date and time from the server you are using is only the first step. Don’t let a wrong time zone or PHP date format throw you off your feet!
Contents
PHP DateTime Format: Main Tips
- Time and date PHP functions allow you to get date and time from the server you’re using.
- These functions are inbuilt into the PHP core.
- Keep in mind that these functions are dependant on your server’s locale setting.
Runtime Configuration
When using these functions to set PHP DateTime format, remember that how they behave will be affected by the settings located in php.ini:
Name | Description | Default | PHP Version |
---|---|---|---|
date.timezone | Default timezone (is used by all PHP date/time functions) | «» | PHP 5.1 and newer |
date.default_latitude | Default latitude (is used by date_sunrise() and date_sunset()) | «31.7667» | PHP 5.0 and newer |
date.default_longitude | Default longitude (is used by date_sunrise() and date_sunset()) | «35.2333» | PHP 5.0 and newer |
date.sunrise_zenith | Default sunrise zenith (is used by date_sunrise() and date_sunset()) | «90.83» | PHP 5.0 and newer |
date.sunset_zenith | Default sunset zenith (is used by date_sunrise() and date_sunset()) | «90.83» | PHP 5.0 and up |
Theory is great, but we recommend digging deeper!
PHP Facebook Messenger Bot
BitDegree Foundation VSI ©
Time And Date Functions
Analyze the table below. It is a handy guide for the inbuilt functions that can be used for all your needs when it comes to setting the PHP DateTime format. Feel free to return to it whenever you need a reminder.
Function | Description |
---|---|
checkdate() | Validate Gregorian date |
date_add() | Add days, months, years, hours, minutes, and seconds to date |
date_create_from_format() | Return new DateTime object formatted according to specified format |
date_create() | Return new DateTime object |
date_date_set() | Set new date |
date_default_timezone_get() | Return default timezone used by all PHP date/time functions |
date_default_timezone_set() | Set default timezone used by all PHP date/time functions |
date_diff() | Return difference between two PHP dates |
date_format() | Return PHP date formatted according to specified format |
date_get_last_errors() | Return warnings/errors found in PHP date string |
date_interval_create_from_date_string() | Set up PHP DateInterval from relative parts of string |
date_interval_format() | Format interval |
date_isodate_set() | Set ISO date |
date_modify() | Modify PHP timestamp |
date_offset_get() | Return timezone offset |
date_parse_from_format() | Return associative array with detailed info about specified date, according to specified format |
date_parse() | Return associative array with detailed info about specified date |
date_sub() | Subtract days, months, years, hours, minutes, and seconds from date |
date_sun_info() | Return array containing info about sunset/sunrise and twilight begin/end, for specified day and location |
date_sunrise() | Return sunrise time for specified day and location |
date_sunset() | Return sunset time for specified day and location |
date_time_set() | Set PHP time |
date_timestamp_get() | Return Unix PHP timestamp |
date_timestamp_set() | Set date and time based on Unix PHP timestamp |
date_timezone_get() | Return time zone of given DateTime object |
date_timezone_set() | Set time zone for DateTime object |
date() | Format local date and time |
getdate() | Return date/time information of PHP timestamp or current local date/time |
gettimeofday() | Return current time |
gmdate() | Format GMT/UTC date and time |
gmmktime() | Return Unix PHP timestamp for GMT date |
gmstrftime() | Format GMT/UTC date and time according to locale settings |
idate() | Format local time/date as int |
localtime() | Return local time |
microtime() | Return currently available Unix PHP timestamp in microseconds |
mktime() | Return Unix PHP timestamp for date |
strftime() | Format local time and/or date according to locale settings |
strptime() | Parse time/date generated with strftime() |
strtotime() | Parse English textual datetime into Unix PHP timestamp |
time() | Return current time as Unix PHP timestamp |
timezone_abbreviations_list() | Return associative array containing dst, offset, and timezone name |
timezone_identifiers_list() | Return indexed array with all timezone identifiers |
timezone_location_get() | Return location information for a specified timezone |
timezone_name_from_ abbr() | Returns the timezone name from abbreviation |
timezone_name_get() | Return name of timezone |
timezone_offset_get() | Return timezone offset from GMT |
timezone_open() | Create new DateTimeZone object |
timezone_transitions_get() | Return all transitions for timezone |
timezone_version_get() | Return version of timezone db |
List of Predefined Constants
There are also a few predefined constants that can be used in PHP date formatting. Take a look at their names and descriptions: