Как прибавить к дате 1 день?
Я не программист, но занимаюсь одним сайтом как администратор. Потребовалось прибавить к дате 1 день. Мне кажется что это нужно сделать вот тут:
Не подскажете, как это все прописать?
3 ответа 3
Выберите тот вариант, который подходит:
Если в общем случае, можно и strtotime заставить «переводить часы», тут я просто прибавил 86400 секунд (один день) к дате.
Тут можно уже и +5 weeks написать и что угодно вместо +1 day
Заработал вот такой вариант:
Всё ещё ищете ответ? Посмотрите другие вопросы с метками php дата или задайте свой вопрос.
Похожие
Подписаться на ленту
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
дизайн сайта / логотип © 2021 Stack Exchange Inc; материалы пользователей предоставляются на условиях лицензии cc by-sa. rev 2021.9.16.40224
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
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.
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.
Increase days to php current Date()
How do I add a certain number of days to the current date in PHP?
I already got the current date with:
Just need to add x number of days to it
11 Answers 11
php supports c style date functions. You can add or substract date-periods with English-language style phrases via the strtotime function. examples.
a day is 86400 seconds.
The simplest way to add x no. of days..
OR from specified date.
The date_add() function should do what you want. In addition, check out the docs (unofficial, but the official ones are a bit sparse) for the DateTime object, it’s much nicer to work with than the procedural functions in PHP.
If you need this code in several places then I’d suggest that you add a short function to keep your code simpler and easier to test.
Then you can use it anywhere like this:
Add 15 day to a select element (using «Alive to Die» suggestion)
mktime() is useful for doing date arithmetic and validation, as it will automatically calculate the correct value for out-of-range input.
The advantage of this method is that you can add or subtract any time interval (hours, minutes, seconds, days, months, or years) in an easy to read line of code.
Beware there is a tradeoff in performance, as this code is about 2.5x slower than strtotime(«+1 day») due to all the calls to the date() function. Consider re-using those values if you are in a loop.
Как прибавить к дате 1 день?
я не программист, но занимаюсь одним сайтом как администратор. Потребовалось прибавить к дате 1 день. Мне кажется что это нужно сделать вот тут:
Помощь в написании контрольных, курсовых и дипломных работ здесь.

Как использовать функцию Date_add не могу разобраться Вот что у меня 2
Спасибо! У меня заработал вот такой вариант:
Помощь в написании контрольных, курсовых и дипломных работ здесь.

Доброго всем времени суток. В общем, наверное, сабж. Если так, то киньте ссылочки соответствующие.

как к текущей дате time() прибавить календарный месяц

Добрый вечер! У меня возникла проблема, есть время по Гринвичу которая лежит в бд, мне необходимо.

Здравствуйте, подскажите пожалуйста есть форма на ней кнопка и поле, в поле в «значение по.
















