"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Add Minutes to a DateTime String in PHP?

How to Add Minutes to a DateTime String in PHP?

Published on 2024-11-14
Browse:838

How to Add Minutes to a DateTime String in PHP?

Adding Minutes to Date Time in PHP

In PHP, adding minutes to a datetime is a straightforward task. However, it may require a specific approach depending on the datetime format.

As mentioned in the inquiry, the given datetime format is "year-month-day hour:minute", e.g., "2011-11-17 05:05". To modify this datetime by adding minutes:

可以使用 DateTime 类和 DateInterval 类:

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

In this code:

  1. $minutes_to_add represents the number of minutes to increment.
  2. $time is created as a DateTime object from the given string.
  3. $time->add() method is used with a DateInterval object to specify the modification.
  4. DateInterval('PT' . $minutes_to_add . 'M') creates an interval representing the specified minutes.
  5. $time is updated with the modified datetime.
  6. $stamp formats the modified datetime and stores it in the desired "year-month-day hour:minute" format.

The ISO 8601 standard is utilized for duration representation, where "P{y}Y{m1}M{d}DT{h}H{m2}M{s}S" denotes a duration of {y} years, {m1} months, {d} days, and so on.

For instance, "P1Y2DT5S" corresponds to 1 year, 2 days, and 5 seconds.

In the provided example, "PT" signifies a time interval, followed by "5M", which represents adding 5 minutes.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3