Convert SQL Server Date to mm-yyyy

I am trying to convert my date, which (e.g. 2012-04-20 05:54:59) formats to mm-yyyy. I came across some solutions that say that you will need to convert to varchar. Is there a way to use the convert function?

Thanks:)

+5
source share
4 answers

You can use the FORMAT function, available from SQL Server 2012 onwards:

 DECLARE @myDate DATETIME = '2012-04-20 05:54:59' SELECT FORMAT(@myDate, 'MM-yyyy') 

Conclusion:

 04-2012 
+11
source

There may be a more elegant way to remove this, but below works.

 Declare @dt datetime = GETDATE() SELECT LEFT('0' + CAST(MONTH(@dt) as varchar(2)),2) + '-' + CAST(YEAR(@dt) as char(4)) 

btw is my regular cheat for converting dates here , but I don't see MM-YYYY as one of the formats.

+5
source

Since you are using SQL Server 2014, you can use FORMAT , which is the best and you can apply this:

 SELECT CONVERT(VARCHAR(2),MONTH(yourDateTimeField)) + '-' + CONVERT(VARCHAR(4),YEAR(yourDateTimeField)) AS [MM-YYYY] FROM yourTable ORDER BY yourDateTimeField 
+3
source
  select [MM-YYYY] = right(convert(varchar(10),getdate(),105),7) 

enter image description here

+3
source

Source: https://habr.com/ru/post/1214615/


All Articles