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#?
This format of date is a combination of year plus a relative day number within the year, which is more correctly called an ordinal date. A typical example is 2013-348 in the format YYYYDDD. This is equivalent to a calendar date of December 14 th 2013.
Writes date values in the form ddmm<yy>yy or dd/mm/<yy>yy, where a forward slash is the separator and the year appears as either two or four digits.
CCYYMMDD means a calendar date in the format of century, year, month and day, without separators. Sample 1Sample 2Sample 3.
Hmm, I am not sure if there is a more direct way, but this should work
new DateTime(year, 1, 1).AddDays(day - 1);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With