Home > Backend Development > PHP Tutorial > How to Add Minutes to a Date and Time in PHP?

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

Mary-Kate Olsen
Release: 2024-11-11 12:51:02
Original
556 people have browsed it

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

Adding Minutes to Date and Time in PHP

Adding minutes to a datetime is a common task that can be achieved using PHP's built-in DateTime interface. As you mentioned, you've encountered difficulties despite consulting online resources. Let's provide a detailed solution to your problem.

Your input datetime format is a combination of year, month, day, hour, and minute, using the ISO 8601 standard. You aim to add an arbitrary number of minutes to this datetime and return the result in the same format.

Here's a PHP code example that will fulfill your requirement:

<?php

$minutes_to_add = 5; // Let's add 5 minutes

// Initialize a new DateTime object using the input format
$time = new DateTime('2011-11-17 05:05');

// Create a DateInterval object to represent the minutes to add
$interval = new DateInterval('PT' . $minutes_to_add . 'M');

// Add the interval to the datetime using the add() method
$time->add($interval);

// Format the resulting datetime in the original format
$stamp = $time->format('Y-m-d H:i');

echo $stamp; // Output: 2011-11-17 05:10

?>
Copy after login

Here's how the code works:

  1. DateInterval Construction: We construct a DateInterval object using the DateInterval('PT' . $minutes_to_add . 'M') syntax. This syntax uses the ISO 8601 duration format to represent a specific duration (in this case, PT5M for 5 minutes).
  2. Addition to DateTime: We then use the add() method of the DateTime object to add the DateInterval to the original datetime. This operation modifies the datetime in place.
  3. Output Formatting: Finally, we use the format() method of the DateTime object to convert it back into the original Y-m-d H:i format and assign it to $stamp. The echo statement will print the resulting datetime string.

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

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