I have been working on a application that is dealing with dates. I wanted to use a function like DateAdd but that is part of VB.Net.
I created a function that is the same as the DateAdd:
public enum DateInterval { Day, DayOfYear, Hour, Minute, Month, Quarter, Second, Weekday, WeekOfYear, Year, } private DateTime DateAdd(DateInterval interval, double number, DateTime dateValue) { DateTime dtm = dateValue; // DateInterval.DayOfYear and DateInterval.Weekday appear the same // as DateInterval.Day. // Looking at http://msdn.microsoft.com/en-us/library/hcxe65wz(v=vs.71).aspx // also seems to indicate they are the same as DateInterval.Day. switch (interval) { case DateInterval.Day: case DateInterval.DayOfYear: case DateInterval.Weekday: dtm = dateValue.AddDays(number); break; case DateInterval.Hour: dtm = dateValue.AddHours(number); break; case DateInterval.Minute: dtm = dateValue.AddMinutes(number); break; case DateInterval.Month: int months = Convert.ToInt32(number); dtm = dateValue.AddMonths(months); break; case DateInterval.Quarter: int quarters = Convert.ToInt32(number); dtm = dateValue.AddMonths(quarters * 3); break; case DateInterval.Second: dtm = dateValue.AddSeconds(number); break; case DateInterval.WeekOfYear: int weekOfYear = Convert.ToInt32(number); dtm = dateValue.AddDays(weekOfYear * 7); break; case DateInterval.Year: int years = Convert.ToInt32(number); dtm = dateValue.AddYears(years); break; } return dtm; } private DateTime DateAdd(string interval, double number, DateTime dateValue) { Dictionary<string, DateInterval> dct = new Dictionary<string, DateInterval> { {"d", DateInterval.Day}, {"y", DateInterval.DayOfYear}, {"h", DateInterval.Hour}, {"n", DateInterval.Minute}, {"m", DateInterval.Month}, {"q", DateInterval.Quarter}, {"s", DateInterval.Second}, {"w", DateInterval.Weekday}, {"ww", DateInterval.WeekOfYear}, {"yyyy", DateInterval.Year}, }; DateInterval di = DateInterval.Day; if (dct.ContainsKey(interval)) { di = dct[interval]; } else { throw new ArgumentException("Argument 'interval' is not a valid value."); } return DateAdd(di, number, dateValue); } |