- Adding Days or Hours to DateTime in PHP
- Adding Datetime
- Subtraction Datetime
- date_add
- Список параметров
- Возвращаемые значения
- Примеры
- Примечания
- Смотрите также
- Add Days to a Date With PHP DateInterval
- The DateInterval Class
- Adding Days to a Date With PHP DateInterval
- Add Days to Date in PHP
- add Method in DateTime() to Add Days in PHP
- Combination of strtotime() and date() to Add Days to Date in PHP
- date_add() to Add Days to Date in PHP
- Related Article — PHP Date
Adding Days or Hours to DateTime in PHP
To calculate date by adding number of days, months or even years, such as how do we know 15 days after today what date is it? there are different way to find datetime after adding or subtract month and return result as new datetime calculated. In this tutorial I will show how to adding number years, days on any specific datetime in PHP with examples.
Adding Datetime
Example #1 — Using date_add()
date_interval_create_from_date_string() will return an DateInterval object by following relative parts of the string.
Example #2 — Using date_add()
".date_format($date,"Y-m-d h:i:s A"); $day =15; $hour = 8; $minute = 11; // add days hours minutes on datetime object date_add($date,date_interval_create_from_date_string("$day days $hour hours $minute minutes")); //display result in custom format yyyy/mm/dd hour:minute:second echo "\nDate added => ".date_format($date,"Y-m-d h:i:s A"); ?>
Date => 2022-05-31 05:52:44 AM Date added => 2022-06-15 02:03:44 PM
Example #3 — Using strtotime()
". $date; // Add Days and Convert to timestamp value. $timestamp = strtotime($date . ' +1 day 2 hour 3 minutes 2 second'); // Convert timestamp to datetime format $date = date('Y-m-d H:i:s A', $timestamp); //display result echo "\nDate added => ".$date; ?>
Date => 2022-05-31 5:52:44 AM Date added => 2022-06-01 07:55:46 AM
Example #4 — Using modify()
modify("+4 days 5 hour 1 minute"); // print result with custom format echo "Date added => ".date_format($dt,'Y-m-d H:i:s A'); ?>
Subtraction Datetime
Example #1 — Using date_sub()
".date_format($date,"Y-m-d h:i:s A"); $day =15; $hour = 8; $minute = 11; // subtract days hours minutes on datetime object date_sub($date,date_interval_create_from_date_string("$day days $hour hours $minute minutes")); //display result in custom format yyyy/mm/dd hour:minute:second echo "\nDate subtract => ".date_format($date,"Y-m-d h:i:s A"); ?>
Date => 2022-05-31 05:52:44 AM Date subtract => 2022-05-15 09:41:44 PM
Example #2 — Using strtotime()
". $date; // Subtract Days and Convert to timestamp value. $timestamp = strtotime($date . ' -1 day 2 hour 3 minutes 2 second'); // Convert timestamp to datetime format $date = date('Y-m-d H:i:s A', $timestamp); //display result echo "\nDate subtract => ".$date; ?>
Date => 2022-05-31 5:52:44 AM Date subtract => 2022-05-30 07:55:46 AM
Example #3 — Using modify()
modify("-4 days 5 hour 1 minute"); // print result with custom format echo "Date subtract => ".date_format($dt,'Y-m-d H:i:s A'); ?>
Date subtract => 2022-05-27 10:53:44 AM
Hope your will learn how to add days to datetime in PHP with these simple examples. Thank you
Author
Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him
date_add
Прибавляет заданный объект DateInterval к объекту DateTime.
Список параметров
Только для процедурного стиля: Объект DateTime, возвращаемый date_create() . Функция изменяет этот объект.
Возвращаемые значения
Возвращает объект DateTime для применения в цепи методов или FALSE в случае возникновения ошибки.
Примеры
Пример #1 Пример использования DateTime::add()
$date = new DateTime ( ‘2000-01-01’ );
$date -> add (new DateInterval ( ‘P10D’ ));
echo $date -> format ( ‘Y-m-d’ ) . «\n» ;
?>?php
$date = date_create ( ‘2000-01-01’ );
date_add ( $date , date_interval_create_from_date_string ( ’10 days’ ));
echo date_format ( $date , ‘Y-m-d’ );
?>?php
Результат выполнения данных примеров:
Пример #2 Другие примеры с DateTime::add()
$date = new DateTime ( ‘2000-01-01’ );
$date -> add (new DateInterval ( ‘PT10H30S’ ));
echo $date -> format ( ‘Y-m-d H:i:s’ ) . «\n» ;
?php
$date = new DateTime ( ‘2000-01-01’ );
$date -> add (new DateInterval ( ‘P7Y5M4DT4H3M2S’ ));
echo $date -> format ( ‘Y-m-d H:i:s’ ) . «\n» ;
?>
Результат выполнения данного примера:
2000-01-01 10:00:30 2007-06-05 04:03:02
Пример #3 Будьте внимательны при добавлении месяцев
$date = new DateTime ( ‘2000-12-31’ );
$interval = new DateInterval ( ‘P1M’ );
?php
$date -> add ( $interval );
echo $date -> format ( ‘Y-m-d’ ) . «\n» ;
$date -> add ( $interval );
echo $date -> format ( ‘Y-m-d’ ) . «\n» ;
?>
Результат выполнения данного примера:
Примечания
При работе с PHP 5.2 в качестве альтернативы можно воспользоваться функцией DateTime::modify() .
Смотрите также
- DateTime::sub() — Вычитает заданное количество дней, месяцев, лет, часов, минут и секунд из времени объекта DateTime
- DateTime::diff() — Возвращает разницу между двумя DateTime объектами
- DateTime::modify() — Изменение временной метки
Add Days to a Date With PHP DateInterval
Monty Shokeen Last updated Jan 10, 2022
PHP has a lot of methods and functions to help you manipulate dates in a variety of ways. In this quick tip, I will show you how to add days to a date in PHP using the DateInterval class. We will begin with an overview of DateInterval and then move on to actual addition.
The DateInterval Class
The DateInterval class is useful for storing a specific amount of time mentioned in terms of years, months, hours, etc. The constructor for this class accepts the specified interval as a string which starts with P. This P stands for the period. You will also have to use the letter T for intervals which contain a time component, i.e. hours, minutes, and seconds.
The following table lists all the characters used to designate specific periods.
Character | What It Represents |
---|---|
Y | years |
M | months |
W | weeks (converted into days) |
D | days |
H | hours |
M | minutes |
S | seconds |
You might have noticed that M represents both months and minutes, but the ambiguity is resolved by the character T that I mentioned earlier. Since minutes represent the time component of our interval, they will be preceded by a T. Here are some examples to make things clear.
String | Time Interval |
---|---|
P20D | 20 days |
P5Y | 5 years |
P2Y3M | 2 years and 3 months |
PT10M | 10 minutes |
P2Y3MT1H10M | 2 years, 3 months, 1 hour and 10 minutes |
There are two things that you have to remember when specifying the duration.
- You cannot combine weeks with days in PHP versions before 8.0.0. P1W3D will be interpreted as 10 days from PHP 8.0.0 onward but as 3 days in earlier versions.
- You have to move from the largest to the smallest unit of time when specifying the duration. This means that years will always have to come before months, months before days, and so on.
Adding Days to a Date With PHP DateInterval
Now that we know how to specify date intervals, we will learn how to add days to a date in PHP. We can use the add() method of the DateTime class. Here is an example:
Add Days to Date in PHP
- add Method in DateTime() to Add Days in PHP
- date_add() to Add Days to Date in PHP
Manipulating date string in PHP can be done in many ways, can add or deduct hours, months, years, etc. PHP provides different functions such as DateTime , date_add and combination of strtotime() and date() .
add Method in DateTime() to Add Days in PHP
Using PHP version 5.3 and above, DateTime object and it’s add method can also be a solution. DateTime supports more date formats than strtotime and date . Using an object also easier than arbitrary functions. For example, when comparing two dates, it’s direct in DateTime , but in strtotime , converting the date first to timestamp is necessary.
php $oldDate = "2020-02-27"; $newDate = new DateTime($oldDate); $newDate->add(new DateInterval('P1D')); // P1D means a period of 1 day $fomattedDate = $date->format('Y-m-d'); ?>
The following code will print output:
echo $fomattedDate; //output: 2020-02-28
The hard part of using DateTime() is the DateInterval object. This accepts a valid interval specification. The proper format starts with the letter P which means period , followed by an integer value, then D for the day. If the duration is time, the last part needs to be T .
Combination of strtotime() and date() to Add Days to Date in PHP
The strtotime() is a PHP function which is used to convert an English textual date description to a UNIX timestamp. The strtotime function will accept a string value that represents date-time.
php $oldDate = "2020-02-27"; $date1 = date("Y-m-d", strtotime($oldDate.'+ 1 days')); $date2 = date("Y-m-d", strtotime($oldDate.'+ 2 days')); ?>
The following code will output:
echo $date1; //output: 2020-02-28 echo $date2; //output: 2020-02-29
The above example will accept a date string with proper format and return the new date using strtotime and +1 days . date() function gave the proper format.
Note: To avoid obscurity, it’s recommended to use ISO 8601 (YYYY-MM-DD) format.
date_add() to Add Days to Date in PHP
This approach is the easiest among the others to add days, months, years, hours, minutes and seconds.
$oldDate = date_create("2020-02-27"); date_add($oldDate, date_interval_create_from_date_string("1 day"));
echo date_format($date,"Y-m-d"); //output: 2020-02-28
The above example also add dates to a date string, date_create() creates a DateTime object. date_interval_create_from_date_string() sets up a DateInterval from the parts of the string. Then finally, date_add() incrementes the date value.
Related Article — PHP Date
Copyright © 2023. All right reserved