DateTime with only Year and Day of Year

  • Thread starter Thread starter O.B.
  • Start date Start date
O

O.B.

Does C# provide an operation for converting year and day-of-the-year
(1-365) to a DateTime object?
 
I would first get the first day of the year and subtract one, like so:

DateTime lastDayOfPreviousYear = (new DateTime(year, 1, 1)).AddDays(-1);

Then, you can add the number of days to the lastDayOfPreviousYear and it
will give you the appropriate DateTime:

DateTime dateTime = lastDayOfPreviousYear.AddDays(days);

Of course, you can just get the first date of the year, and subtract one
from the number of days, like so:

DateTime firstDayOfYear = new DateTime(year, 1, 1);
DateTime dateTime = firstDayOfYear.AddDays(days - 1);
 
O.B. said:
Does C# provide an operation for converting year and day-of-the-year
(1-365) to a DateTime object?

No, but you could create a DateTime for your year, and add the number of
days to it like:

int year = 2007;
int day = 186;

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

MessageBox.Show(d.ToShortDateString() + "\n" + d.DayOfYear.ToString());


The subtraction is necessary or you'll end up on day 187.

Chris.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top