Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordinal Date Format C#

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

like image 442
taelor Avatar asked May 15 '09 19:05

taelor


People also ask

What is ordinal date format?

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.

How do you write the date in Ddmmyy format?

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.

What does Cyymmdd mean?

CCYYMMDD means a calendar date in the format of century, year, month and day, without separators. Sample 1Sample 2Sample 3.


2 Answers

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

new DateTime(year, 1, 1).AddDays(day - 1);
like image 124
Bob Avatar answered Sep 28 '22 02:09

Bob


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.

like image 37
Jon Skeet Avatar answered Sep 28 '22 01:09

Jon Skeet