Wildcard27
Wildcard27

Reputation: 1459

Convert Postgres interval to PHP DateInterval

I am saving a value into a Postgres10 interval type field.

When I return the field, I get the following: 3 years 10 mons 1 day 02:18:00

The problem I seem to be having, mostly, is that it would also return 1 day 02:18:00 if the duration is not years and months long.

Is there a clean way to convert this value into a PHP DateInterval object?

I figure I can use regex but that seems a little messy to me.

Upvotes: 0

Views: 966

Answers (1)

Nick
Nick

Reputation: 147206

If you change the interval output style to iso_8601 using

SET intervalstyle = 'iso_8601';

You will get output in the correct format for a call to DateInterval::__construct e.g.

SELECT
 INTERVAL '6 years 5 months 4 days 3 hours 2 minutes 1 second';

Output:

interval
P6Y5M4DT3H2M1S

Demo on dbfiddle

Upvotes: 1

Related Questions