How to Add Minutes to a DateTime String in PHP?

Susan Sarandon
Release: 2024-11-12 00:54:02
Original
817 people have browsed it

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');
Copy after login

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.

The above is the detailed content of How to Add Minutes to a DateTime String 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