php date minus 1 day
DateTime::sub
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
Описание
Список параметров
Возвращаемые значения
Возвращает объект DateTime для применения в цепи методов или false в случае возникновения ошибки.
Примеры
Пример #1 Пример использования DateTime::sub()
Результат выполнения данных примеров:
Пример #2 Другие примеры DateTime::sub()
Результат выполнения данного примера:
Пример #3 Будьте внимательны при вычитании месяцев
= new DateTime ( ‘2001-04-30’ );
$interval = new DateInterval ( ‘P1M’ );
Результат выполнения данного примера:
Смотрите также
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)
Date minus 1 year?
I’ve got a date in this format:
How do I return the same date but 1 year earlier?
8 Answers 8
The strtotime function returns a unix timestamp, to get a formatted string you can use date :
Use strtotime() function:
Using the DateTime object.
Or using now for today
an easiest way which i used and worked well
this worked perfect.. hope this will help someone else too.. 🙂
On my website, to check if registering people is 18 years old, I simply used the following :
After, only compare the the two dates.
Hope it could help someone.
Although there are many acceptable answers in response to this question, I don’t see any examples of the sub method using the \Datetime object: https://www.php.net/manual/en/datetime.sub.php
So, for reference, you can also use a \DateInterval to modify a \Datetime object:
You can use the following function to subtract 1 or any years from a date.
And looking at above examples you can also use the following
Not the answer you’re looking for? Browse other questions tagged php 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.17.40238
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(час, минута, секунда, месяц, день, год) (обратите внимание на то, что месяц и день переставлены местами ). Посмотрите примеры работы:
Полученная разница в секундах будет выглядеть так: 682522661 (обновите страницу и это число поменяется).
Вооружившись знаниями о том, что такое формат 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 день и выведем в формате ‘день.месяц.год’
Результат выполнения кода:
Что вам делать дальше:
Приступайте к решению задач по следующей ссылке: задачи к уроку.
Php date minus 1 day
(PHP 4, PHP 5, PHP 7, PHP 8)
date — Форматирует вывод системной даты/времени
Описание
Список параметров
Возвращаемые значения
Ошибки
Список изменений
Версия | Описание |
---|---|
8.0.0 | timestamp теперь допускает значение null. |
Примеры
Пример #1 Примеры использования функции date()
// установка часового пояса по умолчанию.
date_default_timezone_set ( ‘UTC’ );
// выведет примерно следующее: Monday
echo date ( «l» );
// выведет примерно следующее: Monday 8th of August 2005 03:12:46 PM
echo date ( ‘l jS \of F Y h:i:s A’ );
/* пример использования константы в качестве форматирующего параметра */
// выведет примерно следующее: Mon, 15 Aug 2005 15:12:46 UTC
echo date ( DATE_RFC822 );
Чтобы запретить распознавание символа как форматирующего, следует экранировать его с помощью обратного слеша. Если экранированный символ также является форматирующей последовательностью, то следует экранировать его повторно.
Пример #2 Экранирование символов в функции date()
Пример #3 Пример совместного использования функций date() и mktime()
Данный способ более надёжен, чем простое вычитание и прибавление секунд к метке времени, поскольку позволяет при необходимости гибко осуществить переход на летнее/зимнее время.
Пример #4 Форматирование с использованием date()
// Предположим, что текущей датой является 10 марта 2001, 5:16:18 вечера,
// и мы находимся в часовом поясе Mountain Standard Time (MST)
$today = date ( «F j, Y, g:i a» ); // March 10, 2001, 5:16 pm
$today = date ( «m.d.y» ); // 03.10.01
$today = date ( «j, n, Y» ); // 10, 3, 2001
$today = date ( «Ymd» ); // 20010310
$today = date ( ‘h-i-s, j-m-y, it is w Day’ ); // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date ( ‘\i\t \i\s \t\h\e jS \d\a\y.’ ); // it is the 10th day.
$today = date ( «D M j G:i:s T Y» ); // Sat Mar 10 17:16:18 MST 2001
$today = date ( ‘H:m:s \m \i\s\ \m\o\n\t\h’ ); // 17:03:18 m is month
$today = date ( «H:i:s» ); // 17:16:18
$today = date ( «Y-m-d H:i:s» ); // 2001-03-10 17:16:18 (формат MySQL DATETIME)
?>
Примечания
Смотрите также
User Contributed Notes 20 notes
Things to be aware of when using week numbers with years.
Conclusion:
if using ‘W’ for the week number use ‘o’ for the year.
In order to define leap year you must considre not only that year can be divide by 4!
The correct alghoritm is:
if (year is not divisible by 4) then (it is a common year)
else if (year is not divisible by 100) then (it is a leap year)
else if (year is not divisible by 400) then (it is a common year)
else (it is a leap year)
So the code should look like this:
For Microseconds, we can get by following:
echo date(‘Ymd His’.substr((string)microtime(), 1, 8).’ e’);
FYI: there’s a list of constants with predefined formats on the DateTime object, for example instead of outputting ISO 8601 dates with:
echo date ( ‘Y-m-d\TH:i:sO’ );
?>
You can use
echo date ( DateTime :: ISO8601 );
?>
instead, which is much easier to read.
this how you make an HTML5 tag correctly
It’s common for us to overthink the complexity of date/time calculations and underthink the power and flexibility of PHP’s built-in functions. Consider http://php.net/manual/en/function.date.php#108613
date() will format a time-zone agnostic timestamp according to the default timezone set with date_default_timezone_set(. ). Local time. If you want to output as UTC time use:
$tz = date_default_timezone_get ();
date_default_timezone_set ( ‘UTC’ );
For HTML5 datetime-local HTML input controls (http://www.w3.org/TR/html-markup/input.datetime-local.html) use format example: 1996-12-19T16:39:57
To generate this, escape the ‘T’, as shown below:
If timestamp is a string, date converts it to an integer in a possibly unexpected way:
The example below formats today’s date in three different ways:
The following function will return the date (on the Gregorian calendar) for Orthodox Easter (Pascha). Note that incorrect results will be returned for years less than 1601 or greater than 2399. This is because the Julian calendar (from which the Easter date is calculated) deviates from the Gregorian by one day for each century-year that is NOT a leap-year, i.e. the century is divisible by 4 but not by 10. (In the old Julian reckoning, EVERY 4th year was a leap-year.)
This algorithm was first proposed by the mathematician/physicist Gauss. Its complexity derives from the fact that the calculation is based on a combination of solar and lunar calendars.
At least in PHP 5.5.38 date(‘j.n.Y’, 2222222222) gives a result of 2.6.2040.
So date is not longer limited to the minimum and maximum values for a 32-bit signed integer as timestamp.
Prior to PHP 5.6.23, Relative Formats for the start of the week aligned with PHP’s (0=Sunday,6=Saturday). Since 5.6.23, Relative Formats for the start of the week align with ISO-8601 (1=Monday,7=Sunday). (http://php.net/manual/en/datetime.formats.relative.php)
This can produce different, and seemingly incorrect, results depending on your PHP version and your choice of ‘w’ or ‘N’ for the Numeric representation of the day of the week:
Prior to PHP 5.6.23, this results in:
Today is Sun 2 Oct 2016, day 0 of this week. Day 1 of next week is 10 Oct 2016
Today is Sun 2 Oct 2016, day 7 of this week. Day 1 of next week is 10 Oct 2016
Since PHP 5.6.23, this results in:
Today is Sun 2 Oct 2016, day 0 of this week. Day 1 of next week is 03 Oct 2016
Today is Sun 2 Oct 2016, day 7 of this week. Day 1 of next week is 03 Oct 2016
I’ve tested it pretty strenuously but date arithmetic is complicated and there’s always the possibility I missed something, so please feel free to check my math.
The function could certainly be made much more powerful, to allow you to set different days to be ignored (e.g. «skip all Fridays and Saturdays but include Sundays») or to set up dates that should always be skipped (e.g. «skip July 4th in any year, skip the first Monday in September in any year»). But that’s a project for another time.
$start = strtotime ( «1 January 2010» );
$end = strtotime ( «13 December 2010» );
// Add as many holidays as desired.
$holidays = array();
$holidays [] = «4 July 2010» ; // Falls on a Sunday; doesn’t affect count
$holidays [] = «6 September 2010» ; // Falls on a Monday; reduces count by one
?>
Or, if you just want to know how many work days there are in any given year, here’s a quick function for that 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.