Utilizando a função to_date() no PostgreSQL

1Comments

Quando trabalhamos com datas no PostgreSQL podemos fazer conversões que facilitam o retorno ou até mesmo para usar como comparação entre dados dentro da query ou em sotred procedures.

Nesse post darei alguns exemplos de como podemos aproveitar essa função a nosso favor.

calendar-de Muitas vezes vemos bancos que armazenam datas como varchar (por diversos motivos que talvez se apliquem a cada caso especificamente) e essa função cai como uma quando precisamos puxar essas informações e tratá-las como datas ou trabalhá-las como um período, etc.

A função to_date() do PostgreSQL nos permite converter diversas formas de entrada de string (text/varchar) para o formato data.

Seu formato de chamada é

to_char(param1 [text], param2 [text])

Sendo:
param1
-> String de entrada em qualquer formato de data possível
param2
-> Formato da string informada no param1

Por exemplo: digamos que temos uma string no formato DDMMYYYY ou até mesmo DD/MM/YYYY. Nesse caso, precisaríamos converter para o formato padrão do PostgreSQL que é YYYY-MM-DD.
Usando a função to_date(), poderíamos fazer a conversão dessa forma:

to_date('19032010', 'DDMMYYYY')

ou

to_date('19/03/2010', 'DD/MM/YYYY')

Dessa forma estaremos dizendo ao SGBD que o formato de entrada da data informada está no formato DDMMYYYY ou DD/MM/YYYY e tendo ciência desse formato o SGBD converterá internamente esse formato para o seu padrão e usará essa informação como data e não string e então, poderemos manipular esse dado como data e aproveitar as funcionalidades que o banco nos dá a esse favor.

Existem diversas possibilidades e combinações de uso no formato da data informada. Veja abaixo a relação delas:

Pattern Description
HH hour of day (01-12)
HH12 hour of day (01-12)
HH24 hour of day (00-23)
MI minute (00-59)
SS second (00-59)
MS millisecond (000-999)
US microsecond (000000-999999)
SSSS seconds past midnight (0-86399)
AM, am, PM or pm meridiem indicator (without periods)
A.M., a.m., P.M. or p.m. meridiem indicator (with periods)
Y,YYY year (4 and more digits) with comma
YYYY year (4 and more digits)
YYY last 3 digits of year
YY last 2 digits of year
Y last digit of year
IYYY ISO year (4 and more digits)
IYY last 3 digits of ISO year
IY last 2 digits of ISO year
I last digit of ISO year
BC, bc, AD or ad era indicator (without periods)
B.C., b.c., A.D. or a.d. era indicator (with periods)
MONTH full uppercase month name (blank-padded to 9 chars)
Month full capitalized month name (blank-padded to 9 chars)
month full lowercase month name (blank-padded to 9 chars)
MON abbreviated uppercase month name (3 chars in English, localized lengths vary)
Mon abbreviated capitalized month name (3 chars in English, localized lengths vary)
mon abbreviated lowercase month name (3 chars in English, localized lengths vary)
MM month number (01-12)
DAY full uppercase day name (blank-padded to 9 chars)
Day full capitalized day name (blank-padded to 9 chars)
day full lowercase day name (blank-padded to 9 chars)
DY abbreviated uppercase day name (3 chars in English, localized lengths vary)
Dy abbreviated capitalized day name (3 chars in English, localized lengths vary)
dy abbreviated lowercase day name (3 chars in English, localized lengths vary)
DDD day of year (001-366)
IDDD ISO day of year (001-371; day 1 of the year is Monday of the first ISO week.)
DD day of month (01-31)
D day of the week, Sunday(1) to Saturday(7)
ID ISO day of the week, Monday(1) to Sunday(7)
W week of month (1-5) (The first week starts on the first day of the month.)
WW week number of year (1-53) (The first week starts on the first day of the year.)
IW ISO week number of year (01 – 53; the first Thursday of the new year is in week 1.)
CC century (2 digits) (The twenty-first century starts on 2001-01-01.)
J Julian Day (days since November 24, 4714 BC at midnight)
Q quarter
RM month in uppercase Roman numerals (I-XII; I=January)
rm month in lowercase Roman numerals (i-xii; i=January)
TZ uppercase time-zone name
tz lowercase time-zone name

E podemos também combinar todos esses valores entre si, como exemplifiquei logo acima convertendo uma string no formato DD/MM/YYYY para que o PostgreSQL entenda ela como data.

Para testar, basta brincar com os valores da tabela acima em uma simples query:

SELECT to_date('Jan 5, 2010', 'Mon DD, YYYY')

E nosso resultado será: 2010-01-05

Até mais…

Tags:, , , ,