Php date add 1 day
DateTime::add
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
Description
Adds the specified DateInterval object to the specified DateTime object.
Parameters
Return Values
Returns the DateTime object for method chaining or false on failure.
Examples
Example #1 DateTime::add() example
The above examples will output:
Example #2 Further DateTime::add() examples
The above example will output:
Example #3 Beware when adding months
= new DateTime ( ‘2000-12-31’ );
$interval = new DateInterval ( ‘P1M’ );
The above example will output:
See Also
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?
Adding one day to a date
My code to add one day to a date returns a date before day adding: 2009-09-30 20:24:00 date after adding one day SHOULD be rolled over to the next month: 1970-01-01 17:33:29
I have used pretty similar code before, what am I doing wrong here?
12 Answers 12
For PHP 5.2.0+, you may also do as follows:
It Worked for me: For Current Date
Simple to read and understand way:
The modify() method that can be used to add increments to an existing DateTime value.
Create a new DateTime object with the current date and time:
Once you have the DateTime object, you can manipulate its value by adding or subtracting time periods:
You can read more on the PHP Manual.
I always just add 86400 (seconds in a day):
It’s not the slickest way you could probably do it, but it works!
While I agree with Doug Hays’ answer, I’ll chime in here to say that the reason your code doesn’t work is because strtotime() expects an INT as the 2nd argument, not a string (even one that represents a date)
If you turn on max error reporting you’ll see this as a «A non well formed numeric value» error which is E_NOTICE level.
The following code get the first day of January of current year (but it can be a another date) and add 365 days to that day (but it can be N number of days) using DateTime class and its method modify() and format():
Since you already have an answer to what’s wrong with your code, I can bring another perspective on how you can play with datetimes generally, and solve your problem specifically.
Oftentimes you find yourself posing a problem in terms of solution. This is just one of the reasons you end up with an imperative code. It’s great if it works though; there are just other, arguably more maintainable alternatives. One of them is a declarative code. The point is asking what you need, instead of how to get there.
In your particular case, this can look like the following. First, you need to find out what is it that you’re looking for, that is, discover abstractions. In your case, it looks like you need a date. Not just any date, but the one having some standard representation. Say, ISO8601 date. There are at least two implementations: the first one is a date parsed from an ISO8601-formatted string (or a string in any other format actually), and the second is some future date which is a day later. Thus, the whole code could look like that:
For more examples with datetime juggling check out this one.
adding 1 day to a DATETIME format value
In certain situations I want to add 1 day to the value of my DATETIME formatted variable:
What is the best way to do this?
9 Answers 9
There’s more then one way to do this with DateTime which was introduced in PHP 5.2. Unlike using strtotime() this will account for daylight savings time and leap year.
If you want to do this in PHP:
If you want to add the date in MySQL:
There are some valid values as examples :
So, in your case you can use the following.
If it’s only adding 1 day, then using strtotime again is probably overkill.
You can use as following.
You can also set days as constant and use like below.
I suggest start using Zend_Date classes from Zend Framework. I know, its a bit offtopic, but I’ll like this way 🙂
Using server request time to Add days. Working as expected.
Here ‘+2 days’ to add any number of days.
There is a more concise and intuitive way to add days to php date. Don’t get me wrong, those php expressions are great, but you always have to google how to treat them. I miss auto-completion facility for that.
Here is how I like to handle those cases:
For me, it’s way more intuitive and autocompletion works out of the box. No need to google for the solution each time.
As a nice bonus, you don’t have to worry about formatting the resulting value, it’s already is ISO8601 format.
This is meringue library, there are more examples here.
Add days to a date in PHP
Is there any php function available where I can add days to a date to make up another date? For example, I have a date in the following format: 27-December-2011
If I add 7 to the above, it should give: 03-January-2012.
7 Answers 7
Look at this simple snippet
You can use the add method of DateTime. Anyway this solution works for php version >= 5.3
Actually it’s easier than all that.
You can use a variable instead of the string, of course. It will be great if the people answering the questions, won’t complicate things. Less code, means less time to waste on the server ;).
Change the format string to be whatever you want. (See the documentation for date() ).
Not the answer you’re looking for? Browse other questions tagged php function date or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.16.40232
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Работа с датами в PHP
Учебник PHP
Практика
Важное
Регулярки
Работа с htaccess
Файлы, папки
Сессии и куки
Работа с БД
Практика по работе с БД в PHP
Перед чтением см. новые уроки раздела «Важное», которые появились выше.
Практика
Движок PHP
Продвинутые БД
Аутентификация
Практика
ООП и MVC
Абстрактные классы и интерфейсы
Трейты
ООП Магия
Практика
Практика: классы как набор методов
Для работы с датами в PHP применяются различные функции. Мы начнем изучение с функции time.
Функция time, формат timestamp
Функция time возвращает разницу в секундах между 1-го января 1970 года и текущим моментом времени. Такое представление даты называется форматом timestamp.
Зачем нужен timestamp?
Время в формате timestamp используется для того, чтобы найти разницу между датами в секундах.
С помощью функции time мы можем получить только текущий момент времени. Чтобы получить timestamp за любую дату следует использовать функцию mktime:
Функция mktime
Функция mktime работает аналогично функции time, но, в отличие от нее, принимает параметры: mktime(час, минута, секунда, месяц, день, год) (обратите внимание на то, что месяц и день переставлены местами ). Посмотрите примеры работы:
Полученная разница в секундах будет выглядеть так: 682454727 (обновите страницу и это число поменяется).
Вооружившись знаниями о том, что такое формат timestamp (он нам еще понадобится в дальнейшем), изучим более полезные функции для работы с датами, например, функцию date.
Функция date
Функция date выводит текущие дату и время в заданном формате.
Формат задается управляющими командами (английскими буквами), при этом можно вставлять любые разделители между ними (дефисы, двоеточие и так далее).
Примеры работы с date:
Второй параметр функции date
Функция date имеет второй необязательный параметр, который принимает момент времени в формате timestamp. Если передать этот параметр, то функция date отформатирует не текущий момент времени, а тот, который передан вторым параметром. Этот timestamp можно получить, к примеру, через mktime (но не обязательно):
Функция strtotime
Следующая полезная функция, которую мы разберем, называется strtotime.
К примеру, я могу передать ей строку ‘2025-12-31’ и функция сама разберет, где тут год, где месяц, а где день, и вернет эту дату в формате timestamp.
Все форматы можно посмотреть тут.
Следующий код вернет дату предыдущего понедельника:
Как добавить или отнять дату
Пример 1
Давайте создадим объект с датой за 2025 год, 12 месяц, 31 день, затем прибавим к ней 1 день и выведем в формате ‘день.месяц.год’
Результат выполнения кода:
Пример 2
Давайте создадим объект с датой за 2025 год, 12 месяц, 31 день, затем прибавим к ней 3 дня и выведем в формате ‘день.месяц.год’
Результат выполнения кода:
Пример 3
Давайте создадим объект с датой за 2025 год, 12 месяц, 31 день, затем прибавим к ней 3 дня и 1 месяц и выведем в формате ‘день.месяц.год’
Результат выполнения кода:
Пример 4
Давайте создадим объект с датой за 2025 год, 1 месяц, 1 день, затем отнимем от нее 1 день и выведем в формате ‘день.месяц.год’
Результат выполнения кода:
Что вам делать дальше:
Приступайте к решению задач по следующей ссылке: задачи к уроку.