1

We have an entry in database for an event time left as P1DT3H53M45S, This means 1 day, 3 hours 53 min and 45 sec. I wan to retrieve date from this format.

I can retrieve the duration left by exploding this string and the calculate and then add to current time and create date.

Is there a better way to find the duration left other than exploding ?

4
  • 2
    Regex, it would be better i guess Commented Sep 18, 2014 at 8:01
  • I don't understand how you can explode such string as P1DT3H53M45S. by what separator? Commented Sep 18, 2014 at 8:04
  • if it can be changed, Unix time is better IMHO Commented Sep 18, 2014 at 8:05
  • 1
    That's just a DateInterval format... why not pass it to its constructor... Commented Sep 18, 2014 at 8:06

2 Answers 2

2

No need for explode. Use DateInterval instead:

$interval = new DateInterval('P1DT3H53M45S');
echo $interval->format('%d day, %h hours, %I minutes, %s seconds');
// 1 day, 3 hours, 53 minutes, 45 seconds
Sign up to request clarification or add additional context in comments.

Comments

1

P1DT3H53M45S is not date, but interval. You can use DateInterval class to create a DateInterval object, from which you can format it, or add it to some of your date.

$interval = new DateInterval('P1DT3H53M45S');
print_r($interval);

# format it
echo $interval->format('%d days, %h hours, %i minutes, %s seconds');

# add it to some date
$dt = new DateTime;
$dt->add($interval);
echo $dt->format('Y-m-d H:i:s');

demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.