WebTuts - seomat.com

Your ultimate destination for comprehensive, easy-to-follow web tutorials.

Add a period of time to a Date in PHP

Adding a period of time to a date in PHP involves utilizing the DateTime class and manipulating it using the modify() method.

Utilizing the DateTime class in PHP enables you to append a time period to a date. The constructor of this object takes two parameters:

  1. The first parameter is the desired time value for setting the object's value, which can be specified using a date format, unix timestamp, day interval, or day period;
  2. The second parameter is the timezone in which you wish to assign the date value.

Without parameters, the DateTime object will return the current date and time.

// Set the date
$today = new DateTime(); // returns the current date & time object

$date = new DateTime('2023-12-25'); // Christmas day of 2023 🎅, as object

// Set the date at a specific timezone
$date = new DateTime('2023-10-10', new DateTimeZone('Europe/Bucharest'));

Output the Date in a specific format

In PHP, the DateTime class provides the format method to format date and time according to specific formats. You can use various format characters to represent different parts of the date and time. Here's an example of using the format method:

$date = new DateTime('2023-12-25');
$date->format('j F, Y'); // 25 December, 2023

Output the Date in timestamp format

To get the Unix timestamp from a DateTime object, you can use the getTimestamp method. Here's an example:

$date = new DateTime('2023-12-25');
$date->getTimestamp(); // 1698084173

Append a time period to a Date

In the next example, the modify method is used to add a specified time interval from the date.

$date = new DateTime('2023-12-25'); // 25 December, 2023
$date->modify('+1 day'); // adding 1 day to the date
$date->format('j F, Y'); // 26 December, 2023