I need to 1. convert date into yyyy-mm format, and 2. calculate duration in month from start_date and end_date, e.g. duration = 1 month, ...etc. start_date & end_date are date string in PostgreSQL. I can calculate duration in days and convert date into yyyy-mm format.
to_char(TO_DATE(end_payperiod_date,'MM/DD/YY'), 'YYYY-MM')
For month duration calculation, I don't find to_date() can convert into yyyy-mm format in PostgreSQL. to_char() can show yyyy-mm, but I can't do calculation.
Is there any way, I can convert date into yyyy-mm to do calculation?
Your requirements are unclear. PostgreSQL easily handles dates and date arithmetic. But values like '2019-12' are not dates. I'll throw together a little table for a demonstration of the problems.
PostgreSQL can subtract one date from another, but you don't have dates. You have strings. So cast the char or varchar columns as dates, and take the difference. If your database has been around for a while, odds are good that there are values in those columns that can't be cast to valid dates.
Note that start_month and end_month are the same for
start_month = '2019-12'
despite the difference ranging from one to 61 days. And how you want to calculate the difference between January and March is still unclear.Adapting the query in your comments to the table and column names given here did not return the results you seem to expect.