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?
14 Answers 14
$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');
The ISO 8601 standard for duration is a string in the form of PYMDTHMS where the parts are replaced by a number value indicating how long the duration is.
For example, P1Y2DT5S means 1 year, 2 days, and 5 seconds.
In the example above, we are providing PT5M (or 5 minutes) to the DateInterval constructor.
With date: 2011-11-18 00:00 if I add 5 mins, I get 2012-04-18 00:00 as a result. ` $time = new DateTime($_REQUEST[‘start’]); $time->add(new DateInterval(‘P’ . $duration . ‘M’)); $endTime = $time->format(‘Y-m-d H:i’); echo $endTime; ` Applogies for the formatting, it appears I can’t work this out either today ^_^
@bozdoz It’s not a question of which method is «better». strtotime produces a Unix timestamp as an integer which is helpful if you are for example sorting dates in php. The DateTime class provides options for object and procedural style operations. It’s more readable and also has better support for handling differences between different timezones; for example, if you have a project that outputs dates for numerous different timezones sourced from the same data instance.
@NicholasJohn16 php.net/manual/en/dateinterval.construct.php >> The format starts with the letter P, for «period.» Each duration period is represented by an integer value followed by a period designator. If the duration contains time elements, that portion of the specification is preceded by the letter T.
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("+ minutes");
Both of the top answers are great and work fine, but I prefer this one. Just seems simpler and more intuitive.
$newtimestamp = strtotime('2011-11-17 05:05 + 16 minute'); echo date('Y-m-d H:i:s', $newtimestamp);
If you are no familiar with strtotime yet, you better head to php.net to discover it’s great power 🙂
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.
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 . "
"; //adding 2 minutes $convertedTime = date('Y-m-d H:i:s', strtotime('+2 minutes', strtotime($startTime))); //display the converted time echo '> '.$convertedTime;
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.
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');
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");
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);
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");
The DateInterval class
A date interval stores either a fixed amount of time (in years, months, days, hours etc) or a relative time string in the format that DateTimeImmutable ‘s and DateTime ‘s constructors support.
More specifically, the information in an object of the DateInterval class is an instruction to get from one date/time to another date/time. This process is not always reversible.
A common way to create a DateInterval object is by calculating the difference between two date/time objects through DateTimeInterface::diff() .
Since there is no well defined way to compare date intervals, DateInterval instances are incomparable.
Class synopsis
Properties
The available properties listed below depend on PHP version, and should be considered as readonly.
Number of microseconds, as a fraction of a second.
Is 1 if the interval represents a negative time period and 0 otherwise. See DateInterval::format() .
If the DateInterval object was created by DateTimeImmutable::diff() or DateTime::diff() , then this is the total number of full days between the start and end dates. Otherwise, days will be false .
If the DateInterval object was created by DateInterval::createFromDateString() , then this property’s value will be true , and the date_string property will be populated. Otherwise, the value will be false , and the y to f , invert , and days properties will be populated.
Changelog
Version | Description |
---|---|
8.2.0 | The from_string and date_string properties were added for DateInterval instances that were created using the DateInterval::createFromDateString() method. |
8.2.0 | Only the y to f , invert , and days will be visible. |
7.4.0 | DateInterval instances are incomparable now; previously, all DateInterval instances were considered equal. |
7.1.0 | The f property was added. |
Table of Contents
- DateInterval::__construct — Creates a new DateInterval object
- DateInterval::createFromDateString — Sets up a DateInterval from the relative parts of the string
- DateInterval::format — Formats the interval
Php date interval minutes
- How to get the current Date and Time in PHP ?
- PHP program to change date format
- How to convert DateTime to String using PHP ?
- How to get Time Difference in Minutes in PHP ?
- Return all dates between two dates in an array in PHP
- Sort an array of dates in PHP
- How to get the time of the last modification of the current page in PHP?
- How to convert a Date into Timestamp using PHP ?
- How to add 24 hours to a unix timestamp in php?
- Sort a multidimensional array by date element in PHP
- Convert timestamp to readable date/time in PHP
- PHP | Number of week days between two dates
- PHP | Converting string to Date and DateTime
- How to get last day of a month from date in PHP ?
PHP String Based
- PHP | Change strings in an array to uppercase
- How to convert first character of all the words uppercase using PHP ?
- How to get the last character of a string in PHP ?
- How to convert uppercase string to lowercase using PHP ?
- How to extract Numbers From a String in PHP ?
- How to replace String in PHP ?
- How to Encrypt and Decrypt a PHP String ?
- How to display string values within a table using PHP ?
- How to write Multi-Line Strings in PHP ?
- How to check if a String Contains a Substring in PHP ?
- How to append a string in PHP ?
- How to remove white spaces only beginning/end of a string using PHP ?
- How to Remove Special Character from String in PHP ?
- How to create a string by joining the array elements using PHP ?
- How to prepend a string in PHP ?
PHP Class Based
PHP JSON Based
PHP File Systems Based
get php DateInterval in total ‘minutes’
I am trying to get the PHP «DateInterval» value in «total minutes» value. How to get it? Seems like simple format(«%i minutes») not working? Here is the sample code:
$test = new \DateTime("48 hours"); $interval = $test->diff(new \DateTime());
echo $interval->format('%a total days');
It is showing 2 days as output, which is totally fine. What I am trying to get if to get the value in «total minutes», so I tried:
echo $interval->format('%i total minutes');
The most sense would make to subtract two UNIX timestamps and divide by 60. The DateInterval class is unnecessary here (and apparently not able to handle this).
6 Answers 6
abs((new \DateTime("48 hours"))->getTimestamp() - (new \DateTime)->getTimestamp()) / 60
That’s the easiest way to get the difference in minutes between two DateTime instances.
If you are stuck in a position where all you have is the DateInterval , and you (like me) discover that there seems to be no way to get the total minutes, seconds or whatever of the interval, the solution is to create a DateTime at zero time, add the interval to it, and then get the resulting timestamp:
$timeInterval = //the DateInterval you have; $intervalInSeconds = (new DateTime())->setTimeStamp(0)->add($timeInterval)->getTimeStamp(); $intervalInMinutes = $intervalInSeconds/60; // and so on
I wrote two functions that just calculates the totalTime from a DateInterval. Accuracy can be increased by considering years and months.
function getTotalMinutes(DateInterval $int)< return ($int->d * 24 * 60) + ($int->h * 60) + $int->i; > function getTotalHours(DateInterval $int)< return ($int->d * 24) + $int->h + $int->i / 60; >
Here is the excepted answer as a method in PHP7.2 style:
public static function getMinutesDifference(\DateTime $a, \DateTime $b): int < return abs($a->getTimestamp() - $b->getTimestamp()) / 60; >
function calculateMinutes(DateInterval $int)< $days = $int->format('%a'); return ($days * 24 * 60) + ($int->h * 60) + $int->i; >
This question is about minutes but if you want to recalculate every carry over points (like I needed to) you can use this solution suggested by @glavic in the comments on the php.net man page (simplified and turned into a function):
private function calculateCarryOverPoints(\DateInterval $dateInterval): \DateInterval < $from = new \DateTime; $to = clone $from; // Add time of dateInterval to empty DateTime object $to = $to->add($dateInterval); // Calculate difference between zero DateTime and DateTime with added DateInterval time // Which returns a DateInterval object $diff with correct carry over points (days, hours, minutes, seconds etc.) return $from->diff($to); >