PHP operations with time element

Hi,
Just a basic PHP question but I can't find a solution anywhere...

I have 2 calc elements that get time value under format hh:mm:ss
Now, in a PHP plugin onafterprocess, I'd like to add these 2 times and save the result in db (to use it later in a time field, so hh:mm:ss format would be great).

I tried with strftotime and datetime :

Like :
$heure_depart = "{fk_demandes___heure_depart_calc}";
$duree = "{fk_demandes___duree_calc}";
$heure_ret = strtotime($heure_depart)+strtotime($duree);
$heure_retour = strftime("%H:%M:%S",$heure_ret);

Or :
$heure_depart = "{fk_demandes___heure_depart_calc}";
$duree = "{fk_demandes___duree_calc}";
$start_hour = new DateTime($heure_depart);
$length = new DateTime($duree);
$return_hour = $start_hour->add($length);
$heure_retour = $return_hour->format('%H:%I:%S');

... yet couldn't get it working.

Thanks for any help !
 
Thanks for your answer,
To sum up, I have :
- a time field for departure hour
- a calc field for length
- I want to calculate the return hour and save it in db

I used a bit of this and that and here is now my working code :

PHP:
// Note that $formModel works for almost all PHP events, here I use it in onAfterProcess
$heure_dep = $formModel->getElementData('fk_devis___horaire_depart', true);
//horaire_depart is a time element and I show only hours and minutes, so it returns an array with 2 values : $heure_dep[0] for hours and $heure_dep[1] for minutes
$duree = $formModel->getElementData('fk_demandes___duree_calc', true);
  // duree_calc is a calc element, that returns the time under format hh:mm:ss, so I have to create an array from it
  $duree_arr = explode(":", $duree);
  // we have an array with 2 values for $heure_dep and an array with 3 values for $duree, we want to add hours, minutes and seconds separately with a foreach. As $duree has 3 values, the foreach will return an array with 3 values : hh:mm:ss
  $heure_ret = array();
  foreach (array_keys($heure_dep + $duree_arr) as $key) {
  $heure_ret[$key] = $heure_dep[$key] + $duree_arr[$key];
  // I don't know why, but the operation deletes leading "0" (example "09" is returned "9")... but we need them in our time format so we have to add them with a sprintf
  $heure_ret[$key] = sprintf('%02d', $heure_ret[$key]);
  }
  // now I have an array with 3 values : hours, time and seconds, just need to implode it before saving to db
  $heure_retour = implode(":", $heure_ret);

I think that if we wanted to update a hh:mm time field in form (with updateFormData) we should return a time under format hh:mm... but not sure about that... Hugh could I have your input on this ?
 
We are in need of some funding.
More details.

Thank you.

Members online

Back
Top