In a database table (SQL Server 2012), I have dates saved in the yyyyxxx
format, where xxx
is the day of the year. For example 2015-08-11
Since there is a good answer for the first question, let's talk about the second one.
How about converting DATETIME to this format?
DATENAME function can help to solve it. It's gonna look like that:
SELECT DATENAME(year, @var) + RIGHT('00' + DATENAME(dayofyear, @var), 3)
Get the Year part, convert to datetime + add days
DECLARE @var NVARCHAR(100) = '2015223';
SELECT CAST(LEFT(@var, 4) AS DATETIME) + CAST(RIGHT(@var, 3) AS INT) - 1;
Or:
DECLARE @var NVARCHAR(100) = '2015223';
SELECT DATEADD(dd,CAST(RIGHT(@var, 3) AS INT)-1, CAST(LEFT(@var, 4) AS DATETIME))
Or if yyyyxxx is INT:
DECLARE @var INT = 2015223;
SELECT DATEADD(dd,(@var%1000)-1, CAST(CAST((@var/1000) AS NVARCHAR(100))
AS DATETIME));
LiveDemo