Hello everyone,

i have a problem with calculating my ending time in php, here is the situation:

i get five values,

  • $startdate
  • $startmin
  • $starthour
  • $minute
  • $hour

where $minute and $hour are the event duration times, now what i am trying to achieve is with these values set, i can calculate the ending time, and if necessary, the ending date.

can anyone push me in the right direction?

You need to work in seconds and you need the timestamp for the starting time.

1. Use strtotime to convert a string to a timestamp (format the input string in a obvious format like yyyy-mm-dd hh:mm if you can).

2. Once you have this converted, then convert your duration hours and minutes to seconds.

3. Add the duration seconds to the timstamp.

4. Convert the resulting end timestamp back to a display format using the date command ( e.g. date ("Y-m-d h:i",$end_timestamp).

<?php
$start = strtotime("{$startdate} {$starthour}:{$startmin}");

$end =strtotime("+{$hour} hours +{$minute} minutes",$start);

echo 'Start Time'. date('Y-m-d H:i:s', $start);
echo 'End Time'. date('Y-m-d H:i:s', $start);
?>
<?php
$start = strtotime("{$startdate} {$starthour}:{$startmin}");

$end =strtotime("+{$hour} hours +{$minute} minutes",$start);

echo 'Start Time'. date('Y-m-d H:i:s', $start);
echo 'End Time'. date('Y-m-d H:i:s', $start);
?>

I'm not entirely sure on this as strtotime() isn't my most used function but are the curly brackets you're using within the strtotime() function really necessary? Same for the colon. The reason I ask is because whenever I've used it, I just put the raw date into it and it always came back with the correct unix timestamp.

Also, wouldn't you want to use $end in echo 'End Time'. date('Y-m-d H:i:s', $start); instead of $start? ;)

For new code, strtotime really should be avoided. While we are a considerable amount of time away from Y2k38 and I really don't think you would run into an issue, if your script would ever need to process a date after 2038, maybe like the end date of a 30yr mortgage or something, strtotime will fail. This has been addressed in the DateTime object built into PHP since 5.2.

Now I hope you're working on a version of php > 5.2 as there really is no reason to be on anything less.

$date = new DateTime("{$startdate} {$starthour}:{$startmin}");
$date->modify("+{$hour} hours +{$minute} minutes");
echo $date->format('Y-m-d H:i:s');
commented: good explanation, great code +1

Thanks a lot guys, works great!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.