Как к дате прибавить месяц php
Как добавить месяц к определенной дате с помощью PHP?
я использую now() Функция для получения даты. Я попытался добавить месяц со многими функциями, такими как:
Решение
Вы сделали это сложнее, чем нужно.
strtotime() примет «сейчас», если вы не передадите ему дату и время.
В противном случае, как вы назвали это, вы должны увидеть эту ошибку:
Предупреждение: strtotime () ожидает, что параметр 2 будет целочисленным, строка указана в / tmp / execpad-a8173d5d91cb / source-a8173d5d91cb в строке
Это потому что strtotime() ожидает, что вторым параметром будет метка времени Unix, и вы четко предоставите строку. Закрытое приближение к вашему коду будет
Если дата по-прежнему поступает в базу данных неправильно, значит, у вас есть проблема за пределами вашего кода даты.
Другие решения
Наличие даты в MySQL как 0000-00-00 00:00:00 обычно указывает, что дата, которую вы пытались сохранить в базе данных, не имела допустимого формата / не была распознана как дата MySQL. Может быть, это проблема с тем, как вы вставляете или обновляете значение даты?
Вы также можете напрямую добавить месяц к дате в MySQL без необходимости выполнять вычисления в PHP с помощью встроенной функции. DATE_ADD () MySQL:
Используя это, вы также можете напрямую обновить значение даты до даты, которая на месяц вперед:
(Заменить table_name, column_name, Я бы а также твой идентификационный номер в соответствии с вашими потребностями.)
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?