Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert SQL Server Date to mm-yyyy

I'm trying to convert my Date which is (eg. 2012-04-20 05:54:59) format in into mm-yyyy. I came across some solutions that says you would need to convert into varchar . Is there any way using the Convert function ?

Thanks :)

like image 510
Prateek Daniels Avatar asked Mar 03 '15 22:03

Prateek Daniels


2 Answers

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

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

Output:

04-2012
like image 111
Giorgos Betsos Avatar answered Oct 03 '22 06:10

Giorgos Betsos


There might be a more graceful way to pull this off, but the below works.

Declare @dt datetime = GETDATE() 

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

btw my normal Date Conversion cheat sheet is here, but I'm not seeing MM-YYYY as one of the formats.

like image 31
Jim Horn Avatar answered Oct 03 '22 06:10

Jim Horn