Get Date From Day Of Year - CSharp System

CSharp examples for System:DateTime Year

Description

Get Date From Day Of Year

Demo Code


using System.Globalization;
using System;//  w w  w  .j  a va 2s  .c  o  m

public class Main{
        public static DateTime GetDateFromDayOfYear(int dayOfYear, int year)
        {
            DateTime ret = new DateTime();

            try
            {
                int[] daysInMonths = GetDaysInMonths(year);

                int month = 0;
                int daysPotential = 0;
                int daysUsed = 0;

                for (int i = 0; i < daysInMonths.Length; i++)
                {
                    daysPotential += daysInMonths[i];
                    if (dayOfYear <= daysPotential)
                    {
                        month = i + 1;
                        break;
                    }

                    daysUsed += daysInMonths[i];
                }

                int dayOfMonth = dayOfYear - daysUsed;

                ret = new DateTime(year, month, dayOfMonth);

            }
            catch (Exception e)
            {
                throw new Exception("Exception in GetDateFromDayOfYear: " + e.Message, e);
            }
            return ret;
        }
}

Related Tutorials