Example #1
0
 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;
 }
 public static DateTime SetDayInMonth(this DateTime @this, int day)
 {
     if (day > 0)
     {
         return @this.AddDays([email protected]).AddDays(day);
     }
     else
     {
         return @this.AddMonths(1).AddDays([email protected](1).Day).AddDays(day);
     }
 }
        /// <summary>
        /// Returns the date after n full calendar months have elapsed, starting
        /// from a given date (this).
        /// </summary>
        /// <remarks>
        /// This only works when adding, not subtracting, calendar months.
        /// </remarks>
        public static DateTime AddCalendarMonths(this DateTime dt, int n)
        {
            // Advance n months...
            int y = dt.AddMonths(n).Year;
            int m = dt.AddMonths(n).Month;

            // ...then get (the day after) the last day in that month
            if (dt.Day != 1)
                return new DateTime(y, m, DateTime.DaysInMonth(y,m)).AddDays(1);
            // unless it's the first of the month (special case)
            else
                return dt.AddMonths(n);
        }
 /// <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;
 }
 public static DateTime AddMonths(this DateTime value, int months, bool ignoreSundays)
 {
     int extraDaysToAdd = 0;
     while (ignoreSundays && value.AddMonths(months).AddDays(extraDaysToAdd).DayOfWeek == DayOfWeek.Sunday)
         extraDaysToAdd += months < 0 ? -1 : 1;
     return value.AddDays(extraDaysToAdd);
 }
        public static DateTime AddMonths(this DateTime value, double months, bool ignoreSundays)
        {
            if (months < 0)
                throw new NotImplementedException();        //# not implemented

            if (months == 0)
            {
                int extraDaysToAdd = 0;
                while (ignoreSundays && value.AddDays(extraDaysToAdd).DayOfWeek == DayOfWeek.Sunday)
                    extraDaysToAdd += 1;
                return value.AddDays(extraDaysToAdd);
            }

            if (months < 1)
            {
                const int fixedDaysInMonth = 30;
                int daysToAdd = (int)Math.Floor(fixedDaysInMonth * months);
                int extraDaysToAdd = 0;
                while (ignoreSundays && value.AddDays(daysToAdd + extraDaysToAdd).DayOfWeek == DayOfWeek.Sunday)
                    extraDaysToAdd += 1;
                return value.AddDays(daysToAdd + extraDaysToAdd);
            }
            else
            {
                int monthsFloor = (int)Math.Floor(months);
                return value.AddMonths(monthsFloor).AddMonths(months - monthsFloor, ignoreSundays);
            }
        }
Example #7
0
 public static DateTime NextMonth(this DateTime date)
 {
     if (date.Day != DateTime.DaysInMonth(date.Year, date.Month))
         return date.AddMonths(1);
     else
         return date.AddDays(1).AddMonths(1).AddDays(-1);
 }
Example #8
0
 public static IEnumerable<DateTime> LastSevenMonths(this DateTime dateTime)
 {
     for (var i = 1; i <= 7; i++)
     {
         var lastMonth = dateTime.AddMonths(1 - i);
         yield return new DateTime(lastMonth.Year, lastMonth.Month, 1);
     }
 }
Example #9
0
 ///////////////////////////////////////////////////////////////////////
 public static DateTime NextMonth(this DateTime date)
 {
     DateTime next = date.AddMonths(1);
     next = next.SetDayOfMonth(1);
     next = next.SetHour(0);
     next = next.SetMinute(0);
     next = next.SetSecond(0);
     next = next.SetMillisecond(0);
     return next;
 }
        /// <summary>
        /// Adds the specified number of months to a DateTime. Also sets the day of the month to match what you pass in, or
        /// the max day of the month, whichever is lesser. This function is useful when iterating through months and you
        /// initially start on the 31st and then in subsequent months get moved to 28 but then later want to return to the 31st.
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="numMonths"></param>
        /// <param name="dayToMatch"></param>
        /// <returns></returns>
        public static DateTime AddMonthsMatchDay(this DateTime dt, int numMonths, int dayToMatch)
        {
            // Add the number of months to our original date
            var newDate = dt.AddMonths(numMonths);

            // Find which is less, the day to match or the number of days in the month
            var lesser = NumberExtensions.LesserOf(dayToMatch, newDate.DaysInMonth());

            // Add/Remove the number of days to match what was picked in the previous line as the lesser day
            return newDate.AddDays(lesser - newDate.Day);
        }
Example #11
0
        public static DateTime GetNearFirstDate(this DateTime date)
        {
            if (date.Day == 1)
            {
                return date;
            }

            DateTime nextDate = date.AddMonths(1);

            return new DateTime(nextDate.Year, nextDate.Month, 1);
        }
Example #12
0
    public static DateTime AddMonthsAvoidWeekend(this DateTime dt, int months)
    {
        DateTime temp = dt.AddMonths(months);

        if (temp.DayOfWeek == DayOfWeek.Saturday)
            temp = temp.AddDays(2);

        if (temp.DayOfWeek == DayOfWeek.Sunday)
            temp = temp.AddDays(1);

        return temp;
    }
        /// <summary>
        /// Returns a new <see cref="DateTime"/> that adds the specified number of months to the value of this instance.
        /// </summary>
        /// <param name="dateTime">A <see cref="DateTime"/>.</param>
        /// <param name="months">A number of months. The <paramref name="months"/> parameter can be negative or
        /// positive.</param>
        /// <returns>An object whose value is the sum of the date and time represented by this instance and <paramref
        /// name="months"/>.</returns>
        public static DateTime AddMonths(this DateTime dateTime, double months)
        {
            int wholeMonths = (int)months;
            double partMonth = months % 1.0;

            // Add whole months
            dateTime = dateTime.AddMonths(wholeMonths);

            // Add part month if required
            if (partMonth > 0.0)
            {
                int monthInDays = (dateTime.AddMonths(1) - dateTime).Days;
                dateTime = dateTime.AddDays(Math.Round(monthInDays * partMonth));
            }
            else if (partMonth < 0.0)
            {
                int monthInDays = (dateTime - dateTime.AddMonths(-1)).Days;
                dateTime = dateTime.AddDays(Math.Round(monthInDays * partMonth));
            }

            return dateTime;
        }
Example #14
0
 /// <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 IEnumerable<DateTime> GenerateMonthlyRecurrenceWithCalendarDaySpecification(this DateTime begin, int recurrenceInterval, DateTime repeatUntilDate)
        {
            yield return begin;

              var targetDayOfMonth = begin.Day;

              while (true)
              {
            begin = begin.AddMonths(recurrenceInterval);
            var tempBegin = GetExistingBegin(begin, targetDayOfMonth);

            begin = tempBegin;
            if (begin.Date > repeatUntilDate.Date)
            {
              yield break;
            }
            yield return begin;
              }
        }
Example #16
0
 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;
 }
 public static int CountDaysOfMonth(this DateTime date)
 {
     var nextMonth = date.AddMonths(1);
       return new DateTime(nextMonth.Year, nextMonth.Month, 1).AddDays(-1).Day;
 }
 /// <summary>
 ///     Returns the last day of the month based on the date sent in
 /// </summary>
 /// <param name="date">Date to get the last day from</param>
 /// <returns>The last day of the month</returns>
 public static DateTime LastDayOfMonth(this DateTime date)
 {
     Guard.NotNull(date, "date");
     return date.AddMonths(1).FirstDayOfMonth().AddDays(-1).Date;
 }
Example #19
0
 /// <summary>
 /// 月份结束时间
 /// </summary>
 /// <param name="dateTime"></param>
 /// <returns></returns>
 public static DateTime GetMonthEnd(this DateTime dateTime)
 {
     return new DateTime(dateTime.AddMonths(1).Year, dateTime.AddMonths(1).Month, 1).AddDays(-1);
 }
		/// <summary>
		/// 获得两个日期之间的月数
		/// </summary>
		/// <param name="beginDate"></param>
		/// <param name="endDate"></param>
		/// <returns></returns>
		public static double GetMonthesBetween(this DateTime beginDate, DateTime endDate)
		{
			var months = 0.0;
			for (; beginDate <= endDate; beginDate = beginDate.AddMonths(1))
			{
				months++;
			}
			months = months - (beginDate - endDate).TotalDays / DateTime.DaysInMonth(endDate.Year, endDate.Month);
			return months;
		}
Example #21
0
 public static DateTime AddQuarters(this DateTime dateTime, Int32 quarters)
 {
     return dateTime.AddMonths(quarters * 3);
 }
 /// <summary>
 ///     Returns the last day of the given month.
 /// </summary>
 public static DateTime LastDateInMonth(this DateTime instance)
 {
     return instance.AddMonths(1).FirstDateInMonth().AddDays(-1);
 }
 /// <summary>
 /// Returns a DateTime a number of months in the future. 
 /// </summary>
 /// <param name="self">The DateTime to move</param>
 /// <param name="months">Number of months</param>
 public static DateTime MonthsSince(this DateTime self, int months)
 {
     return self.AddMonths(months);
 }
 /// <summary>
 /// Returns a DateTime a number of months in the past
 /// </summary>
 /// <param name="self">The DateTime to move</param>
 /// <param name="months">Number of months</param>
 public static DateTime MonthsAgo(this DateTime self, int months)
 {
     return self.AddMonths(-months);
 }
Example #25
0
 /// <summary>
 /// Returns a new <see cref="DateTime"/> that adds the specified number of
 /// quarters to the value of this instance.
 /// </summary>
 /// <param name="date">A valid <see cref="DateTime"/> instance.</param>
 /// <param name="value">A number of whole and fractional quarters.
 /// The <paramref name="value"/> parameter can be negative or positive.</param>
 /// <returns>A <see cref="DateTime"/> whose value is the sum of the
 /// date and time represented by this instance and the number of quarters
 /// represented by <paramref name="value"/>.</returns>
 /// <exception cref="System.ArgumentOutOfRangeException">
 /// The resulting <see cref="DateTime"/> is less than
 /// <see cref="DateTime.MinValue"/> or greater than
 /// <see cref="DateTime.MaxValue"/>.
 /// </exception>
 public static DateTime AddQuarters(this DateTime date, double value)
 {
     return date.AddMonths(checked((int)value * 3));
 }
 /// <summary>
 /// End of a specific time frame
 /// </summary>
 /// <param name="Date">Date to base off of</param>
 /// <param name="TimeFrame">Time frame to use</param>
 /// <param name="Culture">Culture to use for calculating (defaults to the current culture)</param>
 /// <returns>The end of a specific time frame (TimeFrame.Day is the only one that sets the time to 12:59:59 PM, all else are the beginning of the day)</returns>
 public static DateTime EndOf(this DateTime Date, TimeFrame TimeFrame, CultureInfo Culture = null)
 {
     Culture = Culture.Check(CultureInfo.CurrentCulture);
     if (TimeFrame == TimeFrame.Day)
         return new DateTime(Date.Year, Date.Month, Date.Day, 23, 59, 59);
     if (TimeFrame == TimeFrame.Week)
         return Date.BeginningOf(TimeFrame.Week, Culture).AddDays(6);
     if (TimeFrame == TimeFrame.Month)
         return Date.AddMonths(1).BeginningOf(TimeFrame.Month, Culture).AddDays(-1).Date;
     if (TimeFrame == TimeFrame.Quarter)
         return Date.EndOf(TimeFrame.Quarter, Date.BeginningOf(TimeFrame.Year, Culture), Culture);
     return new DateTime(Date.Year, 12, 31);
 }
 /// <summary>
 /// Returns the last day of the month based on the date sent in
 /// </summary>
 /// <param name="Date">Date to get the last day from</param>
 /// <returns>The last day of the month</returns>
 public static DateTime LastDayOfMonth(this DateTime Date)
 {
     Date.ThrowIfNull("Date");
     return Date.AddMonths(1).FirstDayOfMonth().AddDays(-1).Date;
 }
 public static int GetNumberOfDaysInMonth(this DateTime date)
 {
     var nextMonth = date.AddMonths(1);
     return new DateTime(nextMonth.Year, nextMonth.Month, 1).AddDays(-1).Day;
 }
Example #29
0
 /// <summary>
 /// <paramref name="start"/>부터 상대적으로 <paramref name="months"/> 개월수 만큼의 기간
 /// </summary>
 /// <param name="start">시작 시각</param>
 /// <param name="months">시간 간격 (월수)</param>
 public static TimeRange GetRelativeMonthPeriod(this DateTime start, int months) {
     return new TimeRange(start, start.AddMonths(months));
 }
Example #30
0
 /// <summary>
 /// Method for getting previous month
 /// </summary>
 /// <param name="date">Date</param>
 /// <returns>Previous mouth</returns>
 public static DateTime GetPreviousMonth(this DateTime date)
 {
     return date.AddMonths(-1);
 }