views:

58

answers:

2

I'm working with an existing database where all dates are stored as integers in the following format: yyyy[3 digit day of year].

For example:

2010-01-01 == 2010001
2010-12-31 == 2010365

I'm using the following SQL to convert to a datetime:

DATEADD(d, 
    CAST(SUBSTRING(
            CAST(NEW_BIZ_OBS_DATE AS VARCHAR), 5, LEN(NEW_BIZ_OBS_DATE) - 4
        ) AS INT) - 1, 
    CAST('1/1/' + SUBSTRING(CAST(NEW_BIZ_OBS_DATE AS VARCHAR),1,4) AS DATETIME))

Does anyone have a more concise way to do this?

A: 

I think at least one simplification can be made:

DATEADD(d, 
    NEW_BIZ_OBS_DATE % 1000 - 1, 
    CAST('1/1/' + SUBSTRING(CAST(NEW_BIZ_OBS_DATE AS VARCHAR),1,4) AS DATETIME)
)

The second term could also be done as follows I think.

    CAST('1/1/' + CAST(NEW_BIZ_OBS_DATE/1000 AS VARCHAR) AS DATETIME)
DVK
+2  A: 

You can do it numerically instead of usings strings:

dateadd(day, NEW_BIZ_OBS_DATE % 1000 - 1,
  dateadd(year, NEW_BIZ_OBS_DATE / 1000 - 2000, '2000-1-1')
)

(Note that 2010356 is not 2010-12-31 but 2010-12-22. 2010365 is 2010-12-31.)

Guffa
Trixy, the second part... I like :)
DVK