views:

596

answers:

3

Problem:

You are given dates in a format of YYYYddd, which is the year, followed by the day of the year, 1 through 365(366). For example today would be 2009135 (5/15/2009).

What is the best way to create a new datetime from this? In Ruby I know there is a constructor that takes two numbers like so

Date.ordinal(2009, 135)

Is there a similar Constructor for C#?

+5  A: 

Hmm, I am not sure if there is a more direct way, but this should work

new DateTime(year, 1, 1).AddDays(day - 1);
Bob
+2  A: 

How about:

new DateTime(ordinal / 1000, 1, 1).AddDays((ordinal % 1000) - 1);

This relies on day 1 of 2009 being represented as 2009001 rather 20091 though. If it's the latter, it's slightly trickier (although still not exactly hard, of course).

I would try to move away from such a format fairly quickly though - it's not exactly a common one, and it's completely unreadable. Assuming the "2009001" format it at least sorts reasonably, but I can't think of much else in its favour.

Jon Skeet
oh trust me, that's why I'm converting it. This is just how its being handed to us. we take that format and import into our database, but convert it to a normal datetime. Btw, I like your answer, It hit me to do it like the first answer, but I would rather do it in one line. Guess its the Ruby in me. And yah, its always coming out in a YYYYddd format.
taelor
btw, I actually just gave the answer to the other person. he only has 4k in points, and I wanna share the love.
taelor
No problem - I don't think losing 15 is going to hurt me too much :)
Jon Skeet
+1  A: 
int year = 2009;
int month = 1;
int day = 1;
int dayOfYear= 135;

DateTime myDate  = new DateTime(year, month, day);
myDate.AddDays(dayOfYear - 1);
chris