DateTime with only Year and Day of Year

DateTime with only Year and Day of Year

Post by O.B. » Fri, 19 Oct 2007 05:47:52


Does C# provide an operation for converting year and day-of-the-year
(1-365) to a DateTime object?
 
 
 

DateTime with only Year and Day of Year

Post by Nicholas P » Fri, 19 Oct 2007 06:04:45


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);


--
- Nicholas Paldino [.NET/C# MVP]
- XXXX@XXXXX.COM

 
 
 

DateTime with only Year and Day of Year

Post by Chris Shep » Fri, 19 Oct 2007 06:07:11


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.