Adding days to datetime php

PHP: Add days to a date.

This is a short tutorial on how to add days to a given date using PHP. To do this, we can either use a combination of date and strtotime or we can take the OO approach and use the DateTime class.

Using the DateTime class to add days to a date.

Let’s start off by looking at a few examples using the DateTime class.

Adding 30 days to a date.

In the following example, I will add 30 days to a given date:

//Using PHP's DateTime object to add 30 days //to a given date. $date = new DateTime('2019-06-10'); //Create a new DateInterval object using P30D. $interval = new DateInterval('P30D'); //Add the DateInterval object to our DateTime object. $date->add($interval); //Print out the result. echo $date->format("Y-m-d");
  1. We created a new DateTime object and passed in the date that we want to add days onto. In this case, I used the 10th of June, 2019. i.e. We want to add 30 days onto the 10th of June, 2019.
  2. We then created a DateInterval object and set the $interval_spec parameter in the constructor to P30D. P30D stands for “a period of 30 days.”
  3. Afterwards, we added this DateInterval to our DateTime object using the add function.
  4. Finally, we printed out the result using the DateTime::format function.
Читайте также:  Рандом си шарп массив

Add 7 days to a date using DateTime.

The PHP snippet above can be easily modified to add 7 days instead of 30. The only thing that needs changing is the line where we instantiated the DateInterval class:

//DateInterval object using 7 days / P7D. $interval = new DateInterval('P7D');

Adding days to today’s date.

If you want to add days to today’s date, then you can simply omit the parameter in the constructor:

//Create a DateTime object w/ no constructor. $date = new DateTime();

The DateTime object above will default to the current timestamp.

Other DateInterval examples.

Here are a few other interval specifications that can be used with the DateInterval class:

  • P1Y: Adds a period of one year.
  • P5D: Adds a period of 5 days.
  • P1D: Adds a period 1 day.
  • P6M: Adds a period of 6 months.
  • P4W: Adds a period of 4 weeks.

As of PHP version 7.1, you can even add microseconds onto a timestamp.

Using date and strtotime.

If you feel more comfortable using the date and strtotime functions, then you can use the following example:

//Using PHP's date and strtotime functions to get //the date 30 days from now. $thirtyDays = date("Y-m-d", strtotime("+30 days")); //Print out the result. echo $thirtyDays;

In the code above, we added 30 days onto the current date.

However, if you are wanting to add days to a given date, then you will need to modify your approach a little:

//Adding +30 days to a given date. $date = '2019-06-10'; $thirtyDaysUnix = strtotime('+30 days', strtotime($date)); echo date("d M Y", $thirtyDaysUnix);

As you can see, the strtotime function is actually pretty useful in the sense that you can almost write exactly what you want in plain English into the first parameter. For example, you can also tell it to add one month:

//+1 month $nextMonth = date("d M Y", strtotime("+1 month")); echo $nextMonth;

Hopefully, you found this guide useful!

Источник

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» ;
?>

$date = date_create ( ‘2000-01-01’ );
date_add ( $date , date_interval_create_from_date_string ( ’10 days’ ));
echo date_format ( $date , ‘Y-m-d’ );
?>

Результат выполнения данных примеров:

Пример #2 Другие примеры с DateTime::add()

$date = new DateTime ( ‘2000-01-01’ );
$date -> add (new DateInterval ( ‘PT10H30S’ ));
echo $date -> format ( ‘Y-m-d H:i:s’ ) . «\n» ;

$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’ );

$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() — Изменение временной метки

Источник

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

Источник

Add Days to Date in PHP

Add Days to Date in PHP

  1. add Method in DateTime() to Add Days in PHP
  2. 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

Источник

Оцените статью