hemc4
hemc4

Reputation: 1633

How to fetch date from string format

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 ?

Upvotes: 1

Views: 58

Answers (2)

Glavić
Glavić

Reputation: 43552

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

Upvotes: 1

Kevin
Kevin

Reputation: 41885

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

Upvotes: 2

Related Questions