0

I have the following string 2015089 or 2016075, for example.

I need to get the result in yyyy/mm/dd format based on the given input.

So, based on 2015089, I get, 2015/mm/dd. dd is a 89th day of 2015 and mm is a month that has 89th day.

How can I do something like that?

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
gene
  • 2,098
  • 7
  • 40
  • 98

1 Answers1

4

I think the simplest way is to convert to a date using dateadd():

select dateadd(day, right(str, 3) - 1, datefromparts(left(str, 4) + 0, 1, 1) )

That is, add one less than the number of days to the beginning of the year. This assumes that Jan 1 is represented as "1" and not "0".

You can then format the date however you like.

In pre-SQL Server 2012, you can do:

select dateadd(day, right(str, 3) - 1, cast(left(str, 4) + '0101' as date))
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786