How to Add Minutes to a Date Time Object in PHP?

Mary-Kate Olsen
Release: 2024-11-15 04:19:02
Original
538 people have browsed it

How to Add Minutes to a Date Time Object in PHP?

Adding Minutes to a Date Time in PHP: A Comprehensive Solution

Question: How can I increment a date time object in PHP by a specified number of minutes while preserving the original format?

Answer:

To effectively add minutes to a date time in PHP, we will employ a combination of the DateTime and DateInterval classes. Here's a detailed breakdown:

$minutes_to_add = 5;

$time = new DateTime('2011-11-17 05:05');
$time->add(new DateInterval('PT' . $minutes_to_add . 'M'));

$stamp = $time->format('Y-m-d H:i');
Copy after login

Explanation:

  1. Instantiating a DateTime Object: We create a DateTime object using the 'new DateTime()' syntax. The parameter passed to it represents the initial date and time.
  2. Creating a DateInterval Object: This class is used to specify the duration to be added to the date time. In our case, 'PT' stands for a period of time, followed by the number of minutes ('5' in this example) and the letter 'M' to indicate minutes.
  3. Adding Duration to Date: The add() method is then used to add the specified duration to the DateTime object.
  4. Formatting the Output: Finally, the format() method returns the date and time in the desired format, preserving the original 'year-month-day hour:minute' structure.

The ISO 8601 standard for duration follows a specific string format. Here, 'P{y}Y{m1}M{d}DT{h}H{m2}M{s}S' represents a duration with various components, such as years ('Y'), months ('M'), days ('D'), hours ('H'), minutes ('M'), and seconds ('S'). In our case, we utilize 'PT5M' to indicate adding 5 minutes to the date time.

The above is the detailed content of How to Add Minutes to a Date Time Object in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template