Convert day of year to datetime in SQL Server

后端 未结 2 426
温柔的废话
温柔的废话 2021-01-20 04:54

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

相关标签:
2条回答
  • 2021-01-20 05:20

    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)
    
    0 讨论(0)
  • 2021-01-20 05:21

    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

    0 讨论(0)
提交回复
热议问题