public static DateTime SetDayInYear(this DateTime @this, int day) { if (day > 0) { return @this.AddDays([email protected]).AddDays(day); } else { return @this.AddYears(1).AddDays([email protected](1).DayOfYear).AddDays(day); } }
public static DateTime AddYearsAndManageLeapYear(this DateTime date, int value) { Contract.Requires(value >= 1 && value <= 9999); int currentYear = date.Year; int diff = value - currentYear; bool currentYearIsLeapYear = DateTime.IsLeapYear(currentYear); bool newYearIsLeapYear = DateTime.IsLeapYear(value); return !currentYearIsLeapYear && newYearIsLeapYear && date.Day == 28 && date.Month == 2 ? date.AddYears(diff).AddDays(1) : date.AddYears(diff); }
public static DateTime Interval(this DateTime date, DateTimePart? intervalType, int? intervalVal) { if (intervalType.HasValue && intervalVal.HasValue) { switch (intervalType.Value) { case DateTimePart.Year: return date.AddYears(intervalVal.Value); case DateTimePart.Month: return date.AddMonths(intervalVal.Value); case DateTimePart.Day: return date.AddDays((double)intervalVal.Value); case DateTimePart.Hour: return date.AddHours((double)intervalVal.Value); case DateTimePart.Munite: return date.AddMinutes((double)intervalVal.Value); case DateTimePart.Second: return date.AddSeconds((double)intervalVal.Value); case DateTimePart.Week: return date.AddDays((double)intervalVal.Value * 7); case DateTimePart.Quarter: return date.AddMonths(intervalVal.Value * 3); } } return date; }
/// <summary> /// Returns a new <see cref="System.DateTimeOffset" /> that minus the provided parameters (<paramref name="years" />, <paramref name="months" />, <paramref name="days" />, <paramref name="hours" />, <paramref name="minutes" />, <paramref name="seconds" />) value/s. /// </summary> /// <param name="source"><see cref="System.DateTimeOffset" /> instance.</param> /// <param name="years">The number of years to reduce.</param> /// <param name="months">The number of months to reduce.</param> /// <param name="days">The number of days to reduce.</param> /// <param name="hours">The number of hours to reduce.</param> /// <param name="minutes">The number of minutes to reduce.</param> /// <param name="seconds">The number of seconds to reduce.</param> /// <returns>Returns a new <see cref="System.DateTimeOffset" /> that minus the provided parameters (<paramref name="years" />, <paramref name="months" />, <paramref name="days" />, <paramref name="hours" />, <paramref name="minutes" />, <paramref name="seconds" />) value/s.</returns> public static DateTimeOffset Ago(this DateTimeOffset source, int years = 0, int months = 0, int days = 0, int hours = 0, int minutes = 0, int seconds = 0) { return source.AddYears(years * -1) .AddMonths(months * -1) .AddDays(days * -1) .AddHours(hours * -1) .AddMinutes(minutes * -1) .AddSeconds(seconds * -1); }
/// <summary> /// Returns a new <see cref="System.DateTime" /> that adds the provided parameters (<paramref name="years" />, <paramref name="months" />, <paramref name="days" />, <paramref name="hours" />, <paramref name="minutes" />, <paramref name="seconds" />) value/s. /// </summary> /// <param name="source"><see cref="System.DateTime" /> instance.</param> /// <param name="years">The number of years to add.</param> /// <param name="months">The number of months to add.</param> /// <param name="days">The number of days to add.</param> /// <param name="hours">The number of hours to add.</param> /// <param name="minutes">The number of minutes to add.</param> /// <param name="seconds">The number of seconds to add.</param> /// <returns>Returns a new <see cref="System.DateTime" /> that adds the provided parameters (<paramref name="years" />, <paramref name="months" />, <paramref name="days" />, <paramref name="hours" />, <paramref name="minutes" />, <paramref name="seconds" />) value/s.</returns> public static DateTime Advance(this DateTime source, int years = 0, int months = 0, int days = 0, int hours = 0, int minutes = 0, int seconds = 0) { return source.AddYears(years) .AddMonths(months) .AddDays(days) .AddHours(hours) .AddMinutes(minutes) .AddSeconds(seconds); }
/////////////////////////////////////////////////////////////////////// public static DateTime NextYear(this DateTime date) { DateTime next = date.AddYears(1); next = next.SetMonth(1); next = next.SetDayOfMonth(1); next = next.SetHour(0); next = next.SetMinute(0); next = next.SetSecond(0); next = next.SetMillisecond(0); return next; }
public static int CalcuateAge(this DateTime theDateTime) { // Bruteforce Age var age = DateTime.Today.Year - theDateTime.Year; if (theDateTime.AddYears(age) > DateTime.Today) { age--; } return age; }
/// <summary> /// Add an interval of time (or some multiple thereof) to a DateTime. /// </summary> public static DateTime AddInterval(this DateTime dt, Time.IntervalType interval, int numberOfIntervals) { if (interval == Time.IntervalType.Day) return dt.AddDays(numberOfIntervals); else if (interval == Time.IntervalType.Week) return dt.AddDays(7 * numberOfIntervals); else if (interval == Time.IntervalType.Month) return dt.AddMonths(numberOfIntervals); else if (interval == Time.IntervalType.Quarter) // won't necessarily work for qtr end dates return dt.AddMonths(3 * numberOfIntervals); else if (interval == Time.IntervalType.Year) return dt.AddYears(numberOfIntervals); else return dt; }
/// <summary> /// Adds a generic AddType to a DateTime object /// </summary> /// <param name="now"><seealso cref="System.DateTime"/></param> /// <param name="adder">Type structure that acts as a switcher for what type of add to perform</param> /// <param name="much">How much AddType to add to each element for creating list of data</param> /// <returns>A DateTime object with the added AddType amounts</returns> public static DateTime Add(this DateTime now, AddType adder, double much) { DateTime ret = now; switch (adder) { case AddType.Years: { ret = now.AddYears((int)much); break; } case AddType.Months: { ret = now.AddMonths((int)much); break; } case AddType.Days: { ret = now.AddDays(much); break; } case AddType.Hours: { ret = now.AddHours(much); break; } case AddType.Minutes: { ret = now.AddMinutes(much); break; } case AddType.Seconds: { ret = now.AddSeconds(much); break; } case AddType.Milliseconds: { ret = now.AddMilliseconds(much); break; } case AddType.Ticks: { ret = now.AddTicks((long)much); break; } } return ret; }
public static int GetDifferenceInFullYearsWith(this DateTime firstDate, DateTime secondDate) { // http://stackoverflow.com/questions/4127363/date-difference-in-years-c-sharp // + http://stackoverflow.com/questions/9/how-do-i-calculate-someones-age-in-c DateTime zeroTime = new DateTime(1, 1, 1); var timeSpan = firstDate - secondDate; var yearResult = (zeroTime + timeSpan).Year - 1; // because we start at year 1 for the Gregorian calendar, we must subtract a year here. // Il peut y avoir des cas à la con : 31/05/2014-01/06/1995 donne 19 ans alors qu'il nous faut 18 ans ! (probablement dû aux années bisextiles) if (firstDate.AddYears(-yearResult) < secondDate) { yearResult--; } return yearResult; }
public static DateTime SubstractTimeStepUnit(this DateTime dt, TimeStepUnit tstep) { switch (tstep) { case TimeStepUnit.Year: return dt.AddYears(-1); case TimeStepUnit.Month: return dt.AddMonths(-1); case TimeStepUnit.Day: return dt.AddDays(-1); case TimeStepUnit.Hour: return dt.AddHours(-1); case TimeStepUnit.Minute: return dt.AddMinutes(-1); case TimeStepUnit.Second: return dt.AddSeconds(-1); } return dt; }
/// <summary> /// Returns a DateTime a number of years in the past /// </summary> /// <param name="self">The DateTime to move</param> /// <param name="years">Number of years</param> public static DateTime YearsAgo(this DateTime self, int years) { return self.AddYears(-years); }
/// <summary> /// Method for getting previous year /// </summary> /// <param name="date">Date</param> /// <returns>Previous year</returns> public static DateTime GetPreviousYear(this DateTime date) { return date.AddYears(-1); }
/// <summary> /// Adds the given centuries to the given DateTime. /// </summary> /// <param name="date">The DateTime to which the centuries have to be added.</param> /// <param name="centuries">The number of centuries to be added.</param> /// <returns>The DateTime after the centuries are added.</returns> public static DateTime AddCenturies(this DateTime date, int centuries) { return date.AddYears(centuries * YEARS_PER_CENTURY); }
/// <summary> /// Adds the given decades to the given DateTime. /// </summary> /// <param name="date">The DateTime to which the decades have to be added.</param> /// <param name="decades">The number of decades to be added.</param> /// <returns>The DateTime after the decades are added.</returns> public static DateTime AddDecades(this DateTime date, int decades) { return date.AddYears(decades * YEARS_PER_DECADE); }
public static DateTime ChangeYear(this DateTime date, int year) { return date.AddYears(year - date.Year); }
/// <summary> /// Adds one year to the given DateTime. /// </summary> /// <param name="date">The given DateTime.</param> /// <returns>The DateTime after one year is added.</returns> public static DateTime AddAYear(this DateTime date) { return date.AddYears(1); }
public static DateTime SubtractYears(this DateTime dateTime, int years) { return dateTime.AddYears(-years); }
public static TimeSpan FromYears(this DateTime dateTime, int years) { return dateTime.AddYears(years) - dateTime; }
public static bool IsNextYear(this DateTime d) { return IsCurrentYear(d.AddYears(-1)); }
public static DateTime SetYear(this DateTime data, int year) { return data.AddYears(year - data.Year); }
/// <summary> /// DateTime.SafeAddYears, /// This is an extension method. /// Adds years to a date time object without the possibility of generating an out of range exception. /// This is useful when the DateTime object might be set to minimum or maximum value. /// </summary> /// <returns>The new date time object.</returns> public static DateTime SafeAddYears(this DateTime initialValue, int years) { try { return initialValue.AddYears(years); } catch (Exception) { return (years > 0) ? DateTime.MaxValue : DateTime.MinValue; ; } }
public static DateTime ToFinancialYear(this DateTime dateTime) { return dateTime.Month >= 9 ? dateTime : dateTime.AddYears(-1); }
/// <summary> /// This Extension Method of the DateTime class decrements a date by the specified TimePeriod. /// </summary> /// <param name="date">The date to decrement.</param> /// <param name="period">The time period to decrement the date by.</param> /// <returns></returns> public static DateTime PreviousPeriod(this DateTime date, TimePeriod period) { DateTime result = new DateTime(0); switch (period) { case TimePeriod.Day: result = new DateTime(date.AddDays(-1).Ticks); break; case TimePeriod.Week: result = new DateTime(date.AddDays(-7).Ticks); break; case TimePeriod.Fortnight: result = new DateTime(date.AddDays(-14).Ticks); break; case TimePeriod.Month: result = new DateTime(date.AddMonths(-1).Ticks); break; case TimePeriod.TwoMonths: result = new DateTime(date.AddMonths(-2).Ticks); break; case TimePeriod.Quarter: result = new DateTime(date.AddMonths(-3).Ticks); break; case TimePeriod.FourMonths: result = new DateTime(date.AddMonths(-4).Ticks); break; case TimePeriod.HalfYear: result = new DateTime(date.AddMonths(-6).Ticks); break; case TimePeriod.Year: result = new DateTime(date.AddYears(-1).Ticks); break; } if (result.Ticks != 0) return result; throw new Exception("Invalid Time Period " + period.ToString()); }
/// <summary> /// Returns a DateTime a number of years in the future. /// </summary> /// <param name="self">The DateTime to move</param> /// <param name="years">Number of years</param> public static DateTime YearsSince(this DateTime self, int years) { return self.AddYears(years); }
/// <summary> /// Subtracts given years from the given DateTime. /// </summary> /// <param name="date">The given DateTime.</param> /// <param name="years">Number of years to be subtracted.</param> /// <returns>The DateTime after the given years are subtracted.</returns> public static DateTime SubtractYears(this DateTime date, int years) { return date.AddYears(years.Negate()); }
/// <summary> /// 해당일자의 주차를 구한다. 문화권(Culture) 및 새해 첫주차에 대한 정의에 따라 주차가 달라진다. /// ref : http://www.simpleisbest.net/archive/2005/10/27/279.aspx /// ref : http://en.wikipedia.org/wiki/ISO_8601#Week_dates /// </summary> /// <remarks> /// <see cref="CalendarWeekRule"/> 값에 따라 WeekOfYear 가 결정된다. /// /// FirstDay : 1월1일이 포함된 주를 무조건 첫째 주로 삼는다. (우리나라, 미국 등의 기준) : .NET의 설정대로 하면 이렇게 된다. /// FirstFourDayWeek : 1월1일이 포함된 주가 4일 이상인 경우에만 그 해의 첫 번째 주로 삼는다. (ISO 8601) /// 예) 한 주의 시작 요일이 일요일이고 1월1일이 일/월/화/수 중 하나이면 1월1일이 포함된 주는 해당 해의 첫 번째 주이다. /// 예) 한 주의 시작 요일이 일요일이고 1월1일이 목/금/토 중 하나이면 1월1일이 포함된 주는 해당 해의 첫 번째 주로 간주하지 않는다. /// 예) 2005년 1월 1일은 토요일이므로 1월1일이 포함된 주는 2005년의 첫 번째 주로 간주하지 않는다. /// FirstFullWeek : 1월의 첫 번째 주가 7일이 아니면 해당 해의 첫 번째 주로 삼지 않는다. /// 예) 한 주의 시작 요일이 일요일인 경우, 1월1일이 일요일이 아니라면 1월1일이 포함된 주는 해당 해의 첫 번째 주로 간주하지 않는다. /// </remarks> /// <param name="moment">주차(WeekOfYear)를 산정하기 위한 일자</param> /// <param name="timeCalendar">주차 계산을 위한 규칙 정보를 가진 TimeCalendar 인스턴스</param> /// <returns>지정된 일자가 속한 Week Of Year를 반환</returns> public static YearAndWeek GetYearAndWeek(this DateTime moment, ITimeCalendar timeCalendar) { timeCalendar.ShouldNotBeNull("timeCalendar"); var culture = timeCalendar.Culture.GetOrCurrentCulture(); var weekRule = timeCalendar.CalendarWeekRule; var firstDayOfWeek = timeCalendar.FirstDayOfWeek; if(IsDebugEnabled) log.Debug("특정일[{0}] 의 주차를 계산합니다. culture=[{1}], weekRule=[{2}], firstDayOfWeek=[{3}]", moment, culture, weekRule, firstDayOfWeek); var week = culture.Calendar.GetWeekOfYear(moment, weekRule, firstDayOfWeek); var year = moment.Year; //!+ NOTE: .NET 라이브러리가 1월1일 기준으로는 정상작동하지만, 12월 31로 계산하면, 무조건 FirstDay 형식으로 작업해버린다. //!+ FirstFourDayWeek Rule에 따르면 12월 31일이 다음해의 첫주차에 속할 경우도 있지만, .NET에서는 53주차로 반환해 버린다. //!+ 예 12월 31일이 월요일 경우 2001년 53주차가 아니라 2002년 1주차가 되어야 한다. //!+ 이를 해결하기 위해 부가적인 작업이 들어간다. // if(weekRule == CalendarWeekRule.FirstFourDayWeek && firstDayOfWeek == DayOfWeek.Monday) { var weekRange = new TimeRange(TimeTool.StartTimeOfWeek(moment, (DayOfWeek?)firstDayOfWeek), DurationUtil.Week); if(moment.Month == 12 && weekRange.HasInside(new DateTime(year + 1, 1, 1))) { var startDate = moment.AddYears(1).StartTimeOfYear(); if((int)startDate.DayOfWeek > (int)firstDayOfWeek && (int)startDate.DayOfWeek - (int)firstDayOfWeek < 4) { year++; week = 1; } } } // NOTE : 연도 보정 (1월인데, Week가 충분히 큰 숫자 이상이라면, 전년도의 주차를 따른다는 것이다. 그러므로 Year를 전년도로 설정해준다. if(moment.Month == 1 && week > 10) year--; var result = new YearAndWeek(year, week); if(IsDebugEnabled) log.Debug("일자[{0}] 의 주차는 [{4}]입니다. culture=[{1}], weekRule=[{2}], firstDayOfWeek=[{3}]", moment, culture, weekRule, firstDayOfWeek, result); return result; }
public static bool IsPreviousYear(this DateTime d) { return IsCurrentYear(d.AddYears(1)); }
/// <summary> /// <paramref name="start"/>부터 상대적으로 <paramref name="years"/> 년수 만큼의 기간 /// </summary> /// <param name="start">시작 시각</param> /// <param name="years">시간 간격 (년수)</param> public static TimeRange GetRelativeYearPeriod(this DateTime start, int years) { return new TimeRange(start, start.AddYears(years)); }
public static DateTime SubtractYears(this DateTime date, int value) { if (value < 0) throw new ArgumentException("Value cannot be less than 0.", "value"); return date.AddYears(value * -1); }