Convert Date to year / month

Asked

Viewed 3,992 times

0

I was able to convert the date to year / month, but I need the date to go like this: 2019/04, but it’s coming out like this: 2019/4

how can I fix this?

SELECT CONVERT(VARCHAR(4), DATEPART (year,'01/04/2019')) + '/' + CONVERT(VARCHAR(4),DATEPART(month,'01/04/2019')) as AnoMes
  • select (Convert(varchar(200), year(Convert(date, '01/04/2019'))) + '/' + Convert(varchar(200), Month(Convert(date, '01/04/2019')))

3 answers

0

Try

-- código #1
SELECT convert (char(7), nome_coluna, 111) as AnoMes
  from tabela;

where column name is stated as date, datetime or some other type of data specific to date storage.
Style 111 refers to the format 'yyyy/mm/dd'.

Example:

-- código #2
declare @data date;
set @data= convert (date, '1/4/2019', 103);  -- dd/mm/aaaa

SELECT convert (char(7), @data, 111);

0

Try it this way:

    select format(CAST('04/01/2019' AS DATE), 'yyyy/MM');

That test I did had to date it as 'MM/dd/yyyy'.

0

Browser other questions tagged

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