Cosmin
Cosmin

Reputation: 954

Adding minutes to time in PHP

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?

Upvotes: 1

Views: 1198

Answers (3)

BeetleJuice
BeetleJuice

Reputation: 40886

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

Upvotes: 2

William J.
William J.

Reputation: 1584

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

Upvotes: 0

Vinod VT
Vinod VT

Reputation: 7164

Try this,

$data['massage_hour_to']  = strtotime("+90 minutes", strtotime($data['massage_hour_from']));

Upvotes: 0

Related Questions