php date прибавить день
Как прибавить к дате 1 день?
Я не программист, но занимаюсь одним сайтом как администратор. Потребовалось прибавить к дате 1 день. Мне кажется что это нужно сделать вот тут:
Не подскажете, как это все прописать?
3 ответа 3
Выберите тот вариант, который подходит:
Если в общем случае, можно и strtotime заставить «переводить часы», тут я просто прибавил 86400 секунд (один день) к дате.
Тут можно уже и +5 weeks написать и что угодно вместо +1 day
Заработал вот такой вариант:
Всё ещё ищете ответ? Посмотрите другие вопросы с метками php дата или задайте свой вопрос.
Похожие
Подписаться на ленту
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
дизайн сайта / логотип © 2021 Stack Exchange Inc; материалы пользователей предоставляются на условиях лицензии cc by-sa. rev 2021.9.17.40238
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
Как прибавить к дате 1 день?
я не программист, но занимаюсь одним сайтом как администратор. Потребовалось прибавить к дате 1 день. Мне кажется что это нужно сделать вот тут:
Помощь в написании контрольных, курсовых и дипломных работ здесь.
Как прибавить кол-во дней к дате
Как использовать функцию Date_add не могу разобраться Вот что у меня 2
Спасибо! У меня заработал вот такой вариант:
Помощь в написании контрольных, курсовых и дипломных работ здесь.
Прибавить заданный интервал к дате
Доброго всем времени суток. В общем, наверное, сабж. Если так, то киньте ссылочки соответствующие.
К текущей дате time() прибавить календарный месяц
как к текущей дате time() прибавить календарный месяц
Получить timezone пользователя и прибавить его к дате, лежащей в БД
Добрый вечер! У меня возникла проблема, есть время по Гринвичу которая лежит в бд, мне необходимо.
Как к текущей дате прибавить 1 день
Здравствуйте, подскажите пожалуйста есть форма на ней кнопка и поле, в поле в «значение по.
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?