1

I'm trying to add 60 or 90 minutes to a given time using PHP.

I've tried doing this in two ways, both ending with an unexpected result.

Input data:

$data['massage_hour_from'] = '09:00:00';
$data['massage_duration'] = 60;

First try:

$data['massage_hour_to'] = date('H:i:s', strtotime('+' . $data['massage_duration'] . ' minutes', strtotime($data['massage_hour_from'])));

Second try:

$datetime = new DateTime($data['massage_date']);
$datetime->setTime($data['massage_hour_from']);
$datetime->modify('+' . $data['massage_duration'] .' minutes');
$data['massage_hour_to'] = $datetime->format('g:i:s');

What am I doing wrong?

Cosmin
  • 864
  • 3
  • 16
  • 34
  • I never pass up the chance to recommend [Carbon](http://carbon.nesbot.com/#gettingstarted). With that said, you could simply get the current time in Unix Timestamp and add 3600 seconds to that(or whatever the duration is). – Andrei Jul 19 '16 at 11:32
  • 2
    `$datetime->setTime($data['massage_hour_from']);`.... `setTime()` takes 3 arguments, hours, minutes, seconds; not a single formatted string – Mark Baker Jul 19 '16 at 11:34
  • Possible duplicate of [Adding minutes to date time in PHP](http://stackoverflow.com/questions/8169139/adding-minutes-to-date-time-in-php) –  Jul 19 '16 at 11:35

3 Answers3

2

I replaced your variable names with shorter ones, but this code works:

$from = '09:00:00'; //starting string
$duration = 90; //in minutes
$date = new DateTime($from);
$date->add(new DateInterval("PT{$duration}M"));//add minutes
$to = $date->format('H:i:s'); // '10:30:00'

Live demo

BeetleJuice
  • 39,516
  • 19
  • 105
  • 165
  • It works in the live demo, but when I try it locally, I get this fatal error: Fatal error: Uncaught exception 'Exception' with message 'DateInterval::__construct(): Unknown or bad format (PT60 ?>M)' – Cosmin Jul 19 '16 at 11:59
  • There is a problem with your implementation. Focus on how you're constructing the string that goes in `DateInterval`. It should be exactly 'PT60M` but you have `PT60 ?>M`. You may find it a good idea to build the string separately and `echo` to the screen until you get it right. Then put it inside `DateInterval`. – BeetleJuice Jul 19 '16 at 12:03
  • Yes, it seemed like an extra `?>` was coming from the form. It works now. – Cosmin Jul 19 '16 at 12:06
0

Try this,

$data['massage_hour_to']  = strtotime("+90 minutes", strtotime($data['massage_hour_from']));
Vinod VT
  • 6,946
  • 11
  • 51
  • 75
0

You can also use DateTime's add method:

$data['massage_hour_from'] = '09:00:00';
$data['massage_duration'] = new DateInterval('PT60M'); 

$massageStart = new DateTime($data['massage_hour_from']);
$massageStart->add($data['massage_duration']);
echo 'Massage ends at: ' . $massageStart->format('H:i:s');

You can read more about the DateInterval class constructor args here

William J.
  • 1,574
  • 15
  • 26