php datetime add datetime
DateTime::add
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
Описание
Список параметров
Возвращаемые значения
Возвращает объект DateTime для применения в цепи методов или false в случае возникновения ошибки.
Примеры
Пример #1 Пример использования DateTime::add()
Результат выполнения данных примеров:
Пример #2 Другие примеры с DateTime::add()
Результат выполнения данного примера:
Пример #3 Будьте внимательны при добавлении месяцев
= new DateTime ( ‘2000-12-31’ );
$interval = new DateInterval ( ‘P1M’ );
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 12 notes
Another simple solution to adding a month but not autocorrecting days to the next month is this.
(Also works for substracting months)
$dt = new DateTime(«2016-01-31»);
Hope this helps someone.
Here is a solution to adding months when you want 2014-10-31 to become 2014-11-30 instead of 2014-12-01.
/**
* Class MyDateTime
*
* Extends DateTime to include a sensible addMonth method.
*
* This class provides a method that will increment the month, and
* if the day is greater than the last day in the new month, it
* changes the day to the last day of that month. For example,
* If you add one month to 2014-10-31 using DateTime::add, the
* result is 2014-12-01. Using MyDateTime::addMonth the result is
* 2014-11-30.
*/
class MyDateTime extends DateTime
<
If you need add() and sub() that don’t modify object values, you can create new methods like this:
class DateTimeEnhanced extends DateTime <
$interval = DateInterval :: createfromdatestring ( ‘+1 day’ );
If you use fraction of seconds, you may have surprises. It only occurs when the sum of the floating point parts results in exactly 1 second (0.5 + 0.5 ou 0.3 + 0.7, for example). See these cases at intervals slightly bigger than 1 second:
To resolve, add 1 second to the interval and f property must be negative (-1.0 plus original value):
What you can do with this function/method is a great example of the philosophy: «just because you can do it doesn’t mean you should». I’m talking about two issues: (1) the number of days in the month which varies from months 1-12 as well as for month 2 which could be leap year (or not); and then issue (2): what if there is the need to specify a large quantity of an interval such that it needs to be re-characterized into broader-scoped intervals (i.e. 184 seconds ==> 3 minutes-4 seconds). Examples in notes elsewhere in the docs for this function illustrate both issues and their undesired effects so I won’t focus on them further. But how did I decide to handle? I’ve gone with four «public» functions and a single «private» function, and without giving you a bunch of code to study, here are their summaries.
**Results/goals.
—any number of days/hours/minutes/seconds can be passed in to add/subtractTime and all of «Y/M/D/H/M/S» values get adjusted as you would expect.
—using adjustYear/Month lets you pass +/- values and only «Y/M» values get modified without having undesirable effects on day values.
—a call to the «recharacterize» function helps ensure proper and desired values are in the intervals prior to calling date_add to let it do its work.
/* results:
1383458399 1383458399 2013-11-03 01:59:59 EDT
1383458400 1383462000 2013-11-03 02:00:00 EST
noticed how the second column went from 1383458399 to 1383462000 even though only 1 second was added?
*/
$TodaySQL = substr(date(DATE_ISO8601 ),0,10)
$LastYearSQL = date(‘Y.m.d’,strtotime(«-1 years»))
$NextMonthEndSQL = date(‘Y.m.d’,strtotime(«+1 months»))
// handy little SQL date formats
//Today
2021-03-24
//Last year
2020.03.24
//Next month
2021.04.24
Remark, that calculations on date are not defined as bijective operations. The Summertime is integrated by mixing two concepts. You should test it beforehead.
Datetime will correct a date after each summation, if a date (29.2.2021 => 1.3.2021) or a datetime (29.3.2020 2:30 am (Europe/Berlin) => 29.3.2020 3:30 or 29.3.2020 1:30)
Be careful when using this function, I may have happened upon a bug in PHP7.
My code is as follows
//get date from post or else fill with today’s date
if (isset($_POST[«from»]))
<
$from = date_create($_POST[«from»]);
>else<
$from = date_create(date(«Y-m-d»));
>
The resultant output is
$from = 2015-12-11
$to = 2015-12-11
In actuality the result should be
$from = 2015-12-10
$to = 2015-12-11
to fix this i needed to change the code to
//get date from post or else fill with today’s date
if (isset($_POST[«from»]))
<
$from = date_create($_POST[«from»]);
>else<
$from = date_create(date(«Y-m-d»));
>
This isn’t strictly the code I wanted. Possible bug?
Класс 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 02|1[012])» ;
$regexpArray [ ‘d’ ] = «(?P 08|[12]2|3[01])» ;
$regexpArray [ ‘-‘ ] = «[-]» ;
$regexpArray [ ‘.’ ] = «[\. /.]» ;
$regexpArray [ ‘:’ ] = «[:]» ;
$regexpArray [ ‘space’ ] = «[\s]» ;
$regexpArray [ ‘H’ ] = «(?P 03|14|22)» ;
$regexpArray [ ‘i’ ] = «(?P37)» ;
$regexpArray [ ‘s’ ] = «(?P54)» ;
DateTime в 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)
Изменение времени
Изменение метки timestamp
Установка часового пояса
Второй параметр при создании объекта — DateTimeZone, он позволяет назначить часовой пояс нашему объекту. Это означает, что мы сможем легко сравнивать два значения времени из разных часовых поясов и получать корректную разницу.
Полный список часовых поясов можно просмотреть на php.net.
Как добавить дни к значению даты
Для изменения значения даты в объекте DateTime можно использовать метод modify(). Он принимает в качестве параметра строковое значение дней, месяцев, года. Например, если хотите прибавить несколько дней, например 3 дня, один месяц и один год:
Сравнение двух дат
Код выше даст нам разницу двух дат в виде DateInterval.
Конвертация номера месяца и имени месяца
Довольно часто приходится получать имя месяца из его порядкового номера, для этого всего лишь нужно указать формат “F” в качестве первого параметра
Получаем количество недель в месяце
Следующий пример поможет вам получить количество недель в определенном месяце года.
Читайте также
Стандартные библиотеки PHP умеют генерировать только целые случайные числа. Однако, возникают задачи где нужно не целое рандомное число с максимально…
Иногда, когда пишешь терминальное приложение (миграции например), хочется кроме стандартного потока, создавать более красочные сообщения и прогресс-бары. Для этого надо использовать управляющие…
DateTime
Описание
Обращается к пространству имён:
Объект класса \Datetime является практически аналогом встроенного в PHP класса \DateTime, но от него не наследуется. Объект класса \DateTime можно получить из объекта PHP-класса с помощью метода \Bitrix\Main\Type\DateTime::createFromPhp или из timestamp с помощью \Bitrix\Main\Type\DateTime::createFromTimestamp :
Методы
Метод | Описание | С версии |
---|---|---|
createFromTimestamp | Метод создаёт объект DateTime из временной метки Unix. | 15.0.7 |
createFromPhp | Метод создаёт объект DateTime объекта \DateTime PHP. | |
createFromUserTime | Метод создаёт DateTime объект из локального времени пользователя с использованием глобальных настроек временной зоны и региональных настроек по умолчанию. | 14.0.18 |
getTimeZone | Метод возвращает объект временной зоны | |
setDefaultTimeZone | Метод устанавливает временную зону по умолчанию. | 14.0.18 |
setTimeZone | Метод устанавливает объект временной зоны. | 14.0.18 |
toString | Метод конвертирует дату в строку с использованием региональных настроек и настроек глобальных временных зон. | |
toUserTime | Метод изменяет время с серверного на время пользователя с использованием настроек глобальных временных зон. | 14.0.18 |
Примеры
Как из объекта получить представление в виде timestamp:
Как из объекта получить представление в виде строки в формате текущего сайта:
Как из объекта получить представление в произвольном формате (используя \Bitrix\Main\Type\DateTime::format ):
Можно указывать смещение в формате DateInterval (но буква P в начале строки необязательна):
При указании смещения следует указывать периоды, от большей единицы до меньшей (например, года, месяцы, часы).
Время из формата текущего сайта:
Фильтр по datetime:
Пользовательские комментарии
Мы будем рады, если разработчики добавят свои комментарии по практическому использованию методов системы.
Для этого нужно всего лишь авторизоваться на сайте
Но помните, что Пользовательские комментарии, несмотря на модерацию, не являются официальной документацией. Ответственность за их использование несет сам пользователь.
Также Пользовательские комментарии не являются местом для обсуждения функционала. По подобным вопросам обращайтесь на форумы.
DateTime::sub
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
Description
Subtracts the specified DateInterval object from the specified DateTime object.
Parameters
Return Values
Returns the DateTime object for method chaining or false on failure.
Examples
Example #1 DateTime::sub() example
The above examples will output:
Example #2 Further DateTime::sub() examples
The above example will output:
Example #3 Beware when subtracting months
= new DateTime ( ‘2001-04-30’ );
$interval = new DateInterval ( ‘P1M’ );
The above example will output:
See Also
User Contributed Notes 6 notes
As noted above when subtracting months, results can be suspect. I needed to create an array of end of month dates for 6 months starting at Oct and going back. Using:
//Instantiate array
$dateset = [];
array:6 [▼
0 => «2018-10-31»
1 => «2018-10-01»
2 => «2018-09-01»
3 => «2018-08-01»
4 => «2018-07-01»
5 => «2018-06-01»
]
array:6 [▼
0 => «2018-10-31»
1 => «2018-09-30»
2 => «2018-08-31»
3 => «2018-07-31»
4 => «2018-06-30»
5 => «2018-05-31»
]
Remark, that calculations on date are not defined as bijective operations. The Summertime is integrated by mixing two concepts. You should test it beforehead.
Datetime will correct a date after each summation, if a date (29.2.2021 => 1.3.2021) or a datetime (29.3.2020 2:30 am (Europe/Berlin) => 29.3.2020 3:30 or 29.3.2020 1:30)