Пример #1
0
        public static DateTime GetRelativeDate(DateTime date, int delta, TimeUnit unit)
        {
            switch (unit)
            {
            case TimeUnit.Day:
                return(date.Add(new TimeSpan(1 * delta, 0, 0, 0)));

            case TimeUnit.Week:
                return(date.Add(new TimeSpan(7 * delta, 0, 0, 0)));

            case TimeUnit.Month:
                int monthIndex0 = date.Month - 1;
                monthIndex0 += delta;
                int year = date.Year;

                //Ensure within 0-11 range, and in/decrement year accordingly
                while (monthIndex0 < 0)
                {
                    --year;
                    monthIndex0 += 12;
                }
                while (monthIndex0 > 11)
                {
                    ++year;
                    monthIndex0 -= 12;
                }
                //Add one to year to get back to range 1-12
                return(new DateTime(year, monthIndex0 + 1, date.Day));

            case TimeUnit.Year:
                return(new DateTime(date.Year + delta, date.Month, date.Day));

            default:
                throw new ArgumentOutOfRangeException("Cannot get relative date for this type of time unit: " + unit.Humanize());
            }
        }