How to convert day of year to date (without timestamp) [Postgresql]?

Asked

Viewed 460 times

1

I have the value 2016001 symbolizing the first day of the year 2016, how do I catch for example the ANO/MES of 2016263?


Example:

ENTRADA: $data = '2016001'
SAÍDA: $anomes = '2016-01'

If only I could do the opposite of that SQL:

SELECT Extract(DOY FROM TIMESTAMP '2016-12-31 23:59:59') The day;

EXIT: 366


EDITED:

So I draw only the day number of the year:

SELECT SUBSTRING(TO_CHAR(2016263, '9999999') FROM 6 FOR 3)

EXIT: 263

Or the easy way:

SELECT RIGHT(2016263::VARCHAR, 3);

EXIT: 263

1 answer

2


A combination of functions may be used to_date and to_char.

The function to_date will convert the varchar you own (2016263) on a date.

The function to_char will convert that date to the year/month format you need to return (2016/09).

select to_char(to_date(cast(2016263 as varchar),'yyyyDDD'),'yyyy/mm');

 to_char 
---------
 2016/09
(1 registro)

https://www.postgresql.org/docs/9.6/static/functions-formatting.html

  • In my case he 2016263 is a whole, so I’ll modify your answer by putting a CAST to get it right! Thanks for the collaboration!

  • Blz @Marcoshenzel

  • They did not let me improve your answer to be correct, they rejected the modifications, but alright, some data will be wrong there in the answer, referring to the data I passed in the question.

  • 1

    No problems, I edited the SQL command

Browser other questions tagged

You are not signed in. Login or sign up in order to post.