Suppose I have given two dates, if difference is one month then it should be display as 30 days.Even months also need to convert into days I have tried with age( date,now()::timestamp without time zone) but it is giving months-dates-years format. ex: 10 mons 24 days 13:57:40.5265.But I need following way. For example if two months difference is there then I need output as 60 days.
2 Answers
Don't use the age() function for date/time arithmetic. It only returns "symbolic" results (which are good enough for human representation, but almost meaningless for date/time calculations; compared to the standard difference).
The standard difference operator (-) returns day-based results for both date, timestamp and timestamp with time zone (the former returns days as int, the latter two return day-based intervals):
From the day-based intervals you can extract days with the extract() function:
select current_date - '2017-01-01',
extract(day from now()::timestamp - '2017-01-01 00:00:00'),
extract(day from now() - '2017-01-01 00:00:00Z');
2 Comments
pozs
@a_horse_with_no_name from the docs age(timestamp, timestamp): Subtract arguments, producing a "symbolic" result that uses years and months, rather than just days, yes technically its type is
interval, but given its (the function's) semantics and the general interval justification rules, it's not meant to be used in date/time arithmetics (maybe in some edge-cases).Both of those will give that result.
select make_interval(days => ((extract(epoch from '2016-04-10'::date) - extract(epoch from '2016-02-10'::date))/(60*60*24))::integer)::text;
select format('%1$s days', ((extract(epoch from '2016-04-10'::date) - extract(epoch from '2016-02-10'::date))/(60*60*24))::integer);
current_date - your_timestamp_column::date