Question

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#?

Was it helpful?

Solution

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

new DateTime(year, 1, 1).AddDays(day - 1);

OTHER TIPS

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.

int year = 2009;
int month = 1;
int day = 1;
int dayOfYear= 135;

DateTime myDate  = new DateTime(year, month, day);
myDate.AddDays(dayOfYear - 1);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top