Jump to content

Sum of time with cents


AlexGentili

Recommended Posts

this works great and does what it should, but if I had a time format with cents, for example
10:00:00.00 I can't make the change, any ideas?

// convert your date to DateTime object

$date = '10:00:00';
$dt = new DateTime($date);
// convert your period to 
DateInterval$hours = '00:25:10'; 

/* this data dynamic */

$parts = explode(':', $hours);
$interval = new DateInterval('PT' . (int)$parts[0] . 'H' . $parts[1] . 'M' . $parts[2] . 'S');

// Add interval to date
$dt->add($interval);// Format date as you needecho $dt->format('H:i:s'); 

 

Link to comment
Share on other sites

I assume you mean milliseconds. Can you describe what you are trying to accomplish? I.e. do you need\want to include milliseconds or is the problem that there is input data with milliseconds that is causing a failure? The solution to your problem could be very different based on what you are trying to accomplish.

The manual shows that the DateTime class does support milliseconds. So, "where" in your code are you wanting to support milliseconds? Will it be the $date, will it be the defined interval, and/or do you need the milliseconds included in the output??? Need some more info.

Link to comment
Share on other sites

Apparently the DateInterval class supports milliseconds, but the default method does not support it as an input value. You need to instead use the createFromDateString class of that method

// convert your date to DateTime object
$date = '10:00:00.500000';
$dt = new DateTime($date);
// convert your period to 
$interval = '00:25:10.300000';

//Extract time parts
list($hours, $minutes, $totalSeconds) = explode(':', $interval);
list($wholeSeconds, $milliSeconds) = explode('.', $totalSeconds);

//Create interval with milliseconds
$intervalString = "{$hours} hours + {$minutes} minutes + {$wholeSeconds} seconds + {$milliSeconds} microseconds";
$interval = DateInterval::createFromDateString($intervalString);

// Add interval to date
$dt->add($interval);// Format date as you needecho $dt->format('H:i:s'); 

echo $dt->format('Y-m-d\TH:i:s.u'); //Output: 2021-11-12T10:25:10.800000

 

  • Like 1
  • Great Answer 1
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.