Maison  >  Article  >  développement back-end  >  Comment ajouter des minutes à un objet date/heure en PHP ?

Comment ajouter des minutes à un objet date/heure en PHP ?

Mary-Kate Olsen
Mary-Kate Olsenoriginal
2024-11-15 04:19:02540parcourir

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');

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.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn