[php] Adding minutes to date time in PHP

I'm really stuck with adding X minutes to a datetime, after doing lots of google'ing and PHP manual reading, I don't seem to be getting anywhere.

The date time format I have is:

2011-11-17 05:05: year-month-day hour:minute

Minutes to add will just be a number between 0 and 59

I would like the output to be the same as the input format with the minutes added.

Could someone give me a working code example, as my attempts don't seem to be getting me anywhere?

This question is related to php date time

The answer is


One more example of a function to do this: (changing the time and interval formats however you like them according to this for function.date, and this for DateInterval):

(I've also written an alternate form of the below function.)

// Return adjusted time.

function addMinutesToTime( $dateTime, $plusMinutes ) {

    $dateTime = DateTime::createFromFormat( 'Y-m-d H:i', $dateTime );
    $dateTime->add( new DateInterval( 'PT' . ( (integer) $plusMinutes ) . 'M' ) );
    $newTime = $dateTime->format( 'Y-m-d H:i' );

    return $newTime;
}

$adjustedTime = addMinutesToTime( '2011-11-17 05:05', 59 );

echo '<h1>Adjusted Time: ' . $adjustedTime . '</h1>' . PHP_EOL . PHP_EOL;

You can do this with native functions easily:

strtotime('+59 minutes', strtotime('2011-11-17 05:05'));

I'd recommend the DateTime class method though, just posted by Tim.


A bit of a late answer, but the method I would use is:

// Create a new \DateTime instance
$date = DateTime::createFromFormat('Y-m-d H:i:s', '2015-10-26 10:00:00');

// Modify the date
$date->modify('+5 minutes');

// Output
echo $date->format('Y-m-d H:i:s');

Or in PHP >= 5.4

echo (DateTime::createFromFormat('Y-m-d H:i:s', '2015-10-26 10:00:00'))->modify('+5 minutes')->format('Y-m-d H:i:s')

If you want to give a variable that contains the minutes.

Then I think this is a great way to achieve this.

$minutes = 10;
$maxAge = new DateTime('2011-11-17 05:05');
$maxAge->modify("+{$minutes} minutes");

$newtimestamp = strtotime('2011-11-17 05:05 + 16 minute');
echo date('Y-m-d H:i:s', $newtimestamp);

result is

2011-11-17 05:21:00

Live demo is here

If you are no familiar with strtotime yet, you better head to php.net to discover it's great power :-)


Use strtotime("+5 minute", $date);


Example:

$date = "2017-06-16 08:40:00";
$date = strtotime($date);
$date = strtotime("+5 minute", $date);
echo date('Y-m-d H:i:s', $date);

I thought this would help some when dealing with time zones too. My modified solution is based off of @Tim Cooper's solution, the correct answer above.

$minutes_to_add = 10;
$time = new DateTime();
**$time->setTimezone(new DateTimeZone('America/Toronto'));**
$time->add(new DateInterval('PT' . $minutes_to_add . 'M'));
$timestamp = $time->format("Y/m/d G:i:s");

The bold line, line 3, is the addition. I hope this helps some folks as well.


PHP's DateTime class has a useful modify method which takes in easy-to-understand text.

$dateTime = new DateTime('2011-11-17 05:05');
$dateTime->modify('+5 minutes');

You could also use string interpolation or concatenation to parameterize it:

$dateTime = new DateTime('2011-11-17 05:05');
$minutesToAdd = 5;
$dateTime->modify("+{$minutesToAdd} minutes");

one line mysql datetime format

$mysql_date_time = (new DateTime())->modify('+15 minutes')->format("Y-m-d H:i:s");

As noted by Brad and Nemoden in their answers above, strtotime() is a great function. Personally, I found the standard DateTime Object to be overly complicated for many use cases. I just wanted to add 5 minutes to the current time, for example.

I wrote a function that returns a date as a string with some optional parameters:
1.) time:String | ex: "+5 minutes" (default = current time)
2.) format:String | ex: "Y-m-d H:i:s" (default = "Y-m-d H:i:s O")

Obviously, this is not a fully featured method. Just a quick and simple function for modifying/formatting the current date.

function get_date($time=null, $format='Y-m-d H:i:s O')
{
    if(empty($time))return date($format);
    return date($format, strtotime($time));
}

// Example #1: Return current date in default format
$date = get_date(); 

// Example #2: Add 5 minutes to the current date
$date = get_date("+5 minutes"); 

// Example #3: Subtract 30 days from the current date & format as 'Y-m-d H:i:s'
$date = get_date("-30 days", "Y-m-d H:i:s"); 

Without using a variable:

 $yourDate->modify("15 minutes");
 echo $yourDate->format( "Y-m-d H:i");

With using a variable:

 $interval= 15;
 $yourDate->modify("+{$interval } minutes");  
 echo $yourDate->format( "Y-m-d H:i");

I don't know why the approach set as solution didn't work for me. So I'm posting here what worked for me in hope it can help anybody:

$startTime = date("Y-m-d H:i:s");

//display the starting time
echo '> '.$startTime . "<br>";

//adding 2 minutes
$convertedTime = date('Y-m-d H:i:s', strtotime('+2 minutes', strtotime($startTime)));

//display the converted time
echo '> '.$convertedTime;

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to time

Date to milliseconds and back to date in Swift How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime how to sort pandas dataframe from one column Convert time.Time to string How to get current time in python and break up into year, month, day, hour, minute? Xcode swift am/pm time to 24 hour format How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time? What does this format means T00:00:00.000Z? How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift? Extract time from moment js object