1

How can I convert

00:00:46.70

to

T0M46S

I try

$date = new DateTime($time); echo $date->format('\P\TG\Hi\M');

but it gives me something like this:

PT0H00M

Note I want duration... not date!

Vladislav Povorozniuc
  • 2,149
  • 25
  • 26
partiz
  • 1,206
  • 2
  • 13
  • 34
  • @Thilo I should can do it with native php function...no with a custom function...I saw that post before – partiz Jun 05 '15 at 00:21
  • You can leave a comment on the other post, asking if there is such a native php function. – Thilo Jun 05 '15 at 00:23
  • Looking at another post (http://stackoverflow.com/a/19082328/14955) your code should work. Don't you just need to add the part about seconds in the format string? – Thilo Jun 05 '15 at 00:25

2 Answers2

0

There is no native function, but you can do it with native object DateTime : calculate the duration from midnight to your time.

<?php

    $time     = new DateTime('00:00:46.70');
    $midnight = new DateTime('00:00:00.00');
    $period   = $midnight->diff($time);

    echo $period->format('T%iM%SS'); //output T0M46S

print_r($period);

Here is a php sandbox to test it

Alexandre Tranchant
  • 4,426
  • 4
  • 43
  • 70
0

Carbon has the solution

function secondsToISO8601Format(int $seconds): string
{
    return Carbon\CarbonInterval::seconds($seconds)->cascade()->spec();
}
Tyteck
  • 135
  • 2
  • 12
  • I think this one works as expected. Carbon library comes with lots of feature to handle date time easier in PHP. It also remove unnecessary data, i.e. if I pass 3621, it will return PT1H21S, I don't need to check whether there is no minutes data and add logic to remove it manually. – Tuhin Feb 21 '23 at 16:53