public static void AddMonths_Invalid(Calendar calendar)
        {
            Assert.ThrowsAny <ArgumentException>(() => calendar.AddMonths(calendar.MaxSupportedDateTime, 1));
            Assert.ThrowsAny <ArgumentException>(() => calendar.AddMonths(calendar.MinSupportedDateTime, -1)); // JapaneseCalendar throws ArgumentException

            AssertExtensions.Throws <ArgumentOutOfRangeException>("months", () => calendar.AddMonths(DateTime.Now, -120001));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("months", () => calendar.AddMonths(DateTime.Now, 120001));
        }
Exemplo n.º 2
0
        private void RenderHeader(TextWriter output, Calendar calendar, DateTime monthLocal)
        {
            DateTime dateTime  = calendar.AddMonths(monthLocal, -1);
            DateTime dateTime2 = calendar.AddMonths(monthLocal, 1);

            output.Write("<div id=\"divDpHdr\" class=\"");
            if (Utilities.IsFlagSet(this.features, 16) || Utilities.IsFlagSet(this.features, 2))
            {
                output.Write("dpHdrWP");
            }
            else
            {
                output.Write("dpHdr");
            }
            output.Write("\">");
            DateTime time = this.sessionContext.IsRtl ? dateTime2 : dateTime;

            this.sessionContext.RenderThemeImage(output, ThemeFileId.PreviousArrow, "vaM fltLeft", new object[]
            {
                "id=\"imgPrev\"",
                SanitizedHtmlString.Format("y=\"{0}\"", new object[]
                {
                    calendar.GetYear(time)
                }),
                SanitizedHtmlString.Format("m=\"{0}\"", new object[]
                {
                    calendar.GetMonth(time)
                })
            });
            DateTime time2 = this.sessionContext.IsRtl ? dateTime : dateTime2;

            this.sessionContext.RenderThemeImage(output, ThemeFileId.NextArrow, "vaM fltRight", new object[]
            {
                "id=\"imgNext\"",
                SanitizedHtmlString.Format("y=\"{0}\"", new object[]
                {
                    calendar.GetYear(time2)
                }),
                SanitizedHtmlString.Format("m=\"{0}\"", new object[]
                {
                    calendar.GetMonth(time2)
                })
            });
            output.Write("<span tabindex=-1 id=\"spanDate\" class=\"vaM\">");
            output.Write(monthLocal.ToString(this.sessionContext.UserCulture.DateTimeFormat.YearMonthPattern).Replace(',', ' '));
            output.Write("</span><span id=\"spanMonthListDropDown\">");
            this.sessionContext.RenderThemeImage(output, ThemeFileId.DownButton3, "vaM", new object[]
            {
                "id=\"imgDropDwn\""
            });
            output.Write("</span></div>");
        }
Exemplo n.º 3
0
        private static IEnumerable <DateTime> GetOccurrences(DateInterval interval, DatePeriod period, Calendar calendar, DateTime start, DateTime end, bool skipWeekends = true)
        {
            var difference = DateSpan.GetDifference(interval, start, end) / period.Quantifier;

            if (start.Kind == DateTimeKind.Utc)
            {
                start = start.ToLocalTime();
            }

            for (var i = 0; i < difference; i++)
            {
                switch (period.Frequency)
                {
                case DatePeriodFrequency.Seconds:
                    var seconds = calendar.AddSeconds(start, period.Quantifier * i);
                    yield return(DeferOccurrenceFallingOnWeekend(calendar, seconds, skipWeekends));

                    break;

                case DatePeriodFrequency.Minutes:
                    var minutes = calendar.AddMinutes(start, period.Quantifier * i);
                    yield return(DeferOccurrenceFallingOnWeekend(calendar, minutes, skipWeekends));

                    break;

                case DatePeriodFrequency.Hours:
                    var hours = calendar.AddHours(start, period.Quantifier * i);
                    yield return(DeferOccurrenceFallingOnWeekend(calendar, hours, skipWeekends));

                    break;

                case DatePeriodFrequency.Days:
                    var days = calendar.AddDays(start, period.Quantifier * i);
                    yield return(DeferOccurrenceFallingOnWeekend(calendar, days, skipWeekends));

                    break;

                case DatePeriodFrequency.Weeks:
                    var weeks = calendar.AddWeeks(start, period.Quantifier * i);
                    yield return(DeferOccurrenceFallingOnWeekend(calendar, weeks, skipWeekends));

                    break;

                case DatePeriodFrequency.Months:
                    var months = calendar.AddMonths(start, period.Quantifier * i);
                    yield return(DeferOccurrenceFallingOnWeekend(calendar, months, skipWeekends));

                    break;

                case DatePeriodFrequency.Years:
                    var years = calendar.AddYears(start, period.Quantifier * i);
                    yield return(DeferOccurrenceFallingOnWeekend(calendar, years, skipWeekends));

                    break;

                default:
                    throw new ArgumentException("Frequency");
                }
            }
        }
 private void VerificationHelper <T>(Calendar calendar, DateTime time, int months) where T : Exception
 {
     Assert.Throws <T>(() =>
     {
         DateTime actual = calendar.AddMonths(time, months);
     });
 }
Exemplo n.º 5
0
    public static void Main()
    {
        // Sets a DateTime to April 3, 2002 of the Gregorian calendar.
        DateTime myDT = new DateTime(2002, 4, 3, new GregorianCalendar());

        // Uses the default calendar of the InvariantCulture.
        Calendar myCal = CultureInfo.InvariantCulture.Calendar;

        // Displays the values of the DateTime.
        Console.WriteLine("April 3, 2002 of the Gregorian calendar:");
        DisplayValues(myCal, myDT);

        // Adds 5 to every component of the DateTime.
        myDT = myCal.AddYears(myDT, 5);
        myDT = myCal.AddMonths(myDT, 5);
        myDT = myCal.AddWeeks(myDT, 5);
        myDT = myCal.AddDays(myDT, 5);
        myDT = myCal.AddHours(myDT, 5);
        myDT = myCal.AddMinutes(myDT, 5);
        myDT = myCal.AddSeconds(myDT, 5);
        myDT = myCal.AddMilliseconds(myDT, 5);

        // Displays the values of the DateTime.
        Console.WriteLine("After adding 5 to each component of the DateTime:");
        DisplayValues(myCal, myDT);
    }
        private void ShowResults_Click(object sender, RoutedEventArgs e)
        {
            // This scenario illustrates time zone support in Windows.Globalization.Calendar class

            // Displayed time zones in addition to the local time zone.
            string[] timeZones = new[] { "UTC", "America/New_York", "Asia/Kolkata" };

            // Store results here.
            StringBuilder results = new StringBuilder();

            // Create default Calendar object
            Calendar calendar      = new Calendar();
            string   localTimeZone = calendar.GetTimeZone();

            // Show current time in local time zone
            results.AppendLine("Current date and time:");
            results.AppendLine(ReportCalendarData(calendar));

            // Show current time in additional time zones
            foreach (string timeZone in timeZones)
            {
                calendar.ChangeTimeZone(timeZone);
                results.AppendLine(ReportCalendarData(calendar));
            }
            results.AppendLine();

            // Change back to local time zone
            calendar.ChangeTimeZone(localTimeZone);

            // Show a time on 14th day of second month of next year.
            // Note the effect of daylight saving time on the results.
            results.AppendLine("Same time on 14th day of second month of next year:");
            calendar.AddYears(1); calendar.Month = 2; calendar.Day = 14;
            results.AppendLine(ReportCalendarData(calendar));
            foreach (string timeZone in timeZones)
            {
                calendar.ChangeTimeZone(timeZone);
                results.AppendLine(ReportCalendarData(calendar));
            }
            results.AppendLine();

            // Change back to local time zone
            calendar.ChangeTimeZone(localTimeZone);

            // Show a time on 14th day of tenth month of next year.
            // Note the effect of daylight saving time on the results.
            results.AppendLine("Same time on 14th day of tenth month of next year:");
            calendar.AddMonths(8);
            results.AppendLine(ReportCalendarData(calendar));
            foreach (string timeZone in timeZones)
            {
                calendar.ChangeTimeZone(timeZone);
                results.AppendLine(ReportCalendarData(calendar));
            }
            results.AppendLine();

            // Display the results
            OutputTextBlock.Text = results.ToString();
        }
Exemplo n.º 7
0
   private static void AddMonths(Calendar cal)
   {
      int months = 11;
      Example.time = date1;

      // <Snippet5>
      returnTime = DateTime.SpecifyKind(cal.AddMonths(time, months), time.Kind);
      // </Snippet5>
      Console.WriteLine(returnTime.Kind == time.Kind);
   }
Exemplo n.º 8
0
        public TimeBucket(DateTime given, DatePart datePart, bool partialStart = false, bool partialEnd = false)
        {
            //todo: exact 0 must not increment or decrement start, end
            Given        = given;
            DatePart     = datePart;
            PartialStart = partialStart;
            PartialEnd   = partialEnd;
            EndPoint     = datePart switch
            {
                DatePart.Minute => new DateTime(Given.Year, Given.Month, Given.Day, Given.Hour,
                                                Given.Minute, 0).AddMinutes(1),
                DatePart.Hour => new DateTime(Given.Year, Given.Month, Given.Day, Given.Hour, 0, 0)
                .AddHours(1),
                DatePart.Day => new DateTime(Given.Year, Given.Month, Given.Day).AddDays(1),
                DatePart.Week => new DateTime(Given.Year, Given.Month, Given.Day)
                .AddDays((int)DayOfWeek.Saturday - (int)Given.DayOfWeek)
                .AddDays(7),
                DatePart.Month => _calendar.AddMonths(
                    new DateTime(Given.Year, Given.Month, Given.Day).AddDays(
                        (_calendar.GetDayOfMonth(Given) - 1) * -1), 1),
                DatePart.Year => _calendar.AddYears(
                    new DateTime(Given.Year, Given.Month, Given.Day).AddDays(
                        (_calendar.GetDayOfYear(Given) - 1) * -1), 1),
                _ => throw new ArgumentOutOfRangeException(nameof(datePart), datePart, null)
            };

            StartPoint = datePart switch
            {
                DatePart.Minute => new DateTime(Given.Year, Given.Month, Given.Day, Given.Hour,
                                                Given.Minute, 0),
                DatePart.Hour => new DateTime(Given.Year, Given.Month, Given.Day, Given.Hour, 0, 0),
                DatePart.Day => new DateTime(Given.Year, Given.Month, Given.Day),
                DatePart.Week => new DateTime(Given.Year, Given.Month, Given.Day).AddDays(
                    (int)DayOfWeek.Saturday - (int)Given.DayOfWeek),
                DatePart.Month => new DateTime(Given.Year, Given.Month, Given.Day).AddDays(
                    (_calendar.GetDayOfMonth(Given) - 1) * -1),
                DatePart.Year => new DateTime(Given.Year, Given.Month, Given.Day).AddDays(
                    (_calendar.GetDayOfYear(Given) - 1) * -1),
                _ => throw new ArgumentOutOfRangeException(nameof(datePart), datePart, null)
            };
        }
        /// <summary>
        /// This is the click handler for the 'Display' button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Display_Click(object sender, RoutedEventArgs e)
        {
            // This scenario illustrates TimeZone support in Windows.Globalization.Calendar class

            // Displayed TimeZones (other than local timezone)
            String[] timeZones = new String[] { "UTC", "America/New_York", "Asia/Kolkata" };

            // Store results here.
            StringBuilder results = new StringBuilder();

            // Create default Calendar object
            Calendar calendar      = new Calendar();
            String   localTimeZone = calendar.GetTimeZone();

            // Show current time in timezones desired to be displayed including local timezone
            results.AppendLine("Current date and time -");
            results.AppendLine(GetFormattedCalendarDateTime(calendar));
            foreach (String timeZone in timeZones)
            {
                calendar.ChangeTimeZone(timeZone);
                results.AppendLine(GetFormattedCalendarDateTime(calendar));
            }
            results.AppendLine();
            calendar.ChangeTimeZone(localTimeZone);

            // Show a time on 14th day of second month of next year in local, GMT, New York and Indian Time Zones
            // This will show if there were day light savings in time
            results.AppendLine("Same time on 14th day of second month of next year -");
            calendar.AddYears(1); calendar.Month = 2; calendar.Day = 14;
            results.AppendLine(GetFormattedCalendarDateTime(calendar));
            foreach (String timeZone in timeZones)
            {
                calendar.ChangeTimeZone(timeZone);
                results.AppendLine(GetFormattedCalendarDateTime(calendar));
            }
            results.AppendLine();
            calendar.ChangeTimeZone(localTimeZone);

            // Show a time on 14th day of 10th month of next year in local, GMT, New York and Indian Time Zones
            // This will show if there were day light savings in time
            results.AppendLine("Same time on 14th day of tenth month of next year -");
            calendar.AddMonths(8);
            results.AppendLine(GetFormattedCalendarDateTime(calendar));
            foreach (String timeZone in timeZones)
            {
                calendar.ChangeTimeZone(timeZone);
                results.AppendLine(GetFormattedCalendarDateTime(calendar));
            }
            results.AppendLine();

            // Display the results
            OutputTextBlock.Text = results.ToString();
        }
Exemplo n.º 10
0
        public static DateTime DateAdd
            (DateInterval Interval, double Number, DateTime DateValue)
        {
            Calendar calendar = CultureInfo.CurrentCulture.Calendar;

            switch (Interval)
            {
            case DateInterval.Year:
                return(calendar.AddYears(DateValue, ToInt(Number)));

            case DateInterval.Quarter:
                return(calendar.AddMonths
                           (DateValue, ToInt(Number * 3.0)));

            case DateInterval.Month:
                return(calendar.AddMonths(DateValue, ToInt(Number)));

            case DateInterval.DayOfYear:
            case DateInterval.Day:
            case DateInterval.Weekday:
                return(DateValue.AddDays(ToInt(Number)));

            case DateInterval.WeekOfYear:
                return(DateValue.AddDays(ToInt(Number * 7.0)));

            case DateInterval.Hour:
                return(DateValue.AddHours(Number));

            case DateInterval.Minute:
                return(DateValue.AddMinutes(Number));

            case DateInterval.Second:
                return(DateValue.AddSeconds(Number));
            }
            throw new ArgumentException
                      (S._("VB_InvalidInterval"), "Interval");
        }
Exemplo n.º 11
0
        private void ValidateDates()
        {
            if (_startDate < _hostedCalendar.MinSupportedDateTime)
            {
                _startDate = _container.MaxMinimumDate;

                if (_startDate < _hostedCalendar.MinSupportedDateTime)
                {
                    _startDate = _hostedCalendar.MinSupportedDateTime;
                }

                int monthLength = _hostedCalendar.GetDaysInMonth(
                    _hostedCalendar.GetYear(_startDate),
                    _hostedCalendar.GetMonth(_startDate),
                    _hostedCalendar.GetEra(_startDate)) - 1;

                _endDate = _startDate.AddDays(monthLength);

                _container.Synchronize(_startDate, _endDate, _markedDay, this);

                return;
            }

            if (_endDate > _hostedCalendar.MaxSupportedDateTime)
            {
                _endDate = _container.MinMaximumDate;

                if (_endDate > _hostedCalendar.MaxSupportedDateTime)
                {
                    _endDate = _hostedCalendar.MaxSupportedDateTime;
                }

                _startDate = _hostedCalendar.AddMonths(_endDate, -1);

                _container.Synchronize(_startDate, _endDate, _markedDay, this);
            }
        }
Exemplo n.º 12
0
        public void AddMonths(DateTime time, int months)
        {
            DateTime result = s_calendar.AddMonths(time, months);

            int  oldYear       = s_calendar.GetYear(time);
            int  oldMonth      = s_calendar.GetMonth(time);
            int  oldDay        = s_calendar.GetDayOfMonth(time);
            long oldTicksOfDay = time.Ticks % TimeSpan.TicksPerDay;
            int  newYear       = s_calendar.GetYear(result);
            int  newMonth      = s_calendar.GetMonth(result);
            int  newDay        = s_calendar.GetDayOfMonth(result);
            long newTicksOfDay = result.Ticks % TimeSpan.TicksPerDay;

            Assert.Equal(oldTicksOfDay, newTicksOfDay);
            Assert.False(newDay > oldDay);
            Assert.False(newYear * 12 + newMonth != oldYear * 12 + oldMonth + months);
        }
Exemplo n.º 13
0
        static void Main(string[] args)
        {
            //DateTime dateTime = new DateTime(2021,4,3,new GregorianCalendar());
            DateTime dateTime = DateTime.Now;
            Calendar myCal    = CultureInfo.InvariantCulture.Calendar;

            Console.WriteLine("Before adding value in datTime");
            DisplayData(myCal, dateTime);
            dateTime = myCal.AddYears(dateTime, 5);
            dateTime = myCal.AddMonths(dateTime, 5);
            dateTime = myCal.AddWeeks(dateTime, 5);
            dateTime = myCal.AddDays(dateTime, 5);
            dateTime = myCal.AddHours(dateTime, 5);
            dateTime = myCal.AddMinutes(dateTime, 5);
            dateTime = myCal.AddSeconds(dateTime, 5);
            dateTime = myCal.AddMilliseconds(dateTime, 5);
            Console.WriteLine();
            Console.WriteLine("After adding 5 value in each of this");
            DisplayData(myCal, dateTime);
            Console.ReadLine();
        }
Exemplo n.º 14
0
        public static DateTime Add(this Period thisPeriod, DateTime dateTime)
        {
            int periodMultiplierAsInt = thisPeriod.GetPeriodMultiplier();

            switch (thisPeriod.period)
            {
            case PeriodEnum.D:
                return(Calendar.AddDays(dateTime, periodMultiplierAsInt));

            case PeriodEnum.W:
                return(Calendar.AddWeeks(dateTime, periodMultiplierAsInt));

            case PeriodEnum.M:
                return(Calendar.AddMonths(dateTime, periodMultiplierAsInt));

            case PeriodEnum.Y:
                return(Calendar.AddYears(dateTime, periodMultiplierAsInt));

            default:
                throw new ArgumentException(string.Format("PeriodEnum '{0}' is not supported in this function", thisPeriod.period));
            }
        }
    public void ChangeDay(int i)
    {
        switch (CurrentViewIndex)
        {
        case (int)State.DAILY:
            lastGivenDate = (calendar.AddDays(lastGivenDate, i));
            break;

        case (int)State.WEEKLY:
            lastGivenDate = (calendar.AddWeeks(lastGivenDate, i));
            break;

        case (int)State.MONTHLY:
            lastGivenDate = (calendar.AddMonths(lastGivenDate, i));
            break;

        case (int)State.ILLEGAL:
        default:
            break;
        }
        RequestView(lastGivenDate);
    }
        void OnPrintDocumentPaginate(object sender, PaginateEventArgs args)
        {
            // Prepare to generate pages
            uint pageNumber = 0;

            calendarPages.Clear();
            Calendar calendar = monthYearSelect1.MonthYear.Clone();

            calendar.Day = 1;
            Brush black = new SolidColorBrush(Colors.Black);

            // For each month
            do
            {
                PrintPageDescription printPageDescription =
                    args.PrintTaskOptions.GetPageDescription(pageNumber);

                // Set Padding on outer Border
                double left  = printPageDescription.ImageableRect.Left;
                double top   = printPageDescription.ImageableRect.Top;
                double right = printPageDescription.PageSize.Width
                               - left - printPageDescription.ImageableRect.Width;
                double bottom = printPageDescription.PageSize.Height
                                - top - printPageDescription.ImageableRect.Height;
                Border border = new Border {
                    Padding = new Thickness(left, top, right, bottom)
                };

                // Use Grid for calendar cells
                Grid grid = new Grid();
                border.Child = grid;
                int numberOfWeeks = (6 + (int)calendar.DayOfWeek + calendar.LastDayInThisMonth) / 7;

                for (int row = 0; row < numberOfWeeks + 1; row++)
                {
                    grid.RowDefinitions.Add(new RowDefinition
                    {
                        Height = new GridLength(1, GridUnitType.Star)
                    });
                }

                for (int col = 0; col < 7; col++)
                {
                    grid.ColumnDefinitions.Add(new ColumnDefinition
                    {
                        Width = new GridLength(1, GridUnitType.Star)
                    });
                }

                // Month and year display at top
                Viewbox viewbox = new Viewbox
                {
                    Child = new TextBlock
                    {
                        Text                = calendar.MonthAsSoloString() + " " + calendar.YearAsString(),
                        Foreground          = black,
                        FontSize            = 96,
                        HorizontalAlignment = HorizontalAlignment.Center
                    }
                };
                Grid.SetRow(viewbox, 0);
                Grid.SetColumn(viewbox, 0);
                Grid.SetColumnSpan(viewbox, 7);
                grid.Children.Add(viewbox);

                // Now loop through the days of the month
                for (int day = 1, row = 1, col = (int)calendar.DayOfWeek;
                     day <= calendar.LastDayInThisMonth; day++)
                {
                    Border dayBorder = new Border
                    {
                        BorderBrush = black,

                        // Avoid double line drawing
                        BorderThickness = new Thickness
                        {
                            Left   = day == 1 || col == 0 ? 1 : 0,
                            Top    = day - 7 < 1 ? 1 : 0,
                            Right  = 1,
                            Bottom = 1
                        },

                        // Put day of month in upper-left corner
                        Child = new TextBlock
                        {
                            Text                = day.ToString(),
                            Foreground          = black,
                            FontSize            = 24,
                            HorizontalAlignment = HorizontalAlignment.Left,
                            VerticalAlignment   = VerticalAlignment.Top
                        }
                    };
                    Grid.SetRow(dayBorder, row);
                    Grid.SetColumn(dayBorder, col);
                    grid.Children.Add(dayBorder);

                    if (0 == (col = (col + 1) % 7))
                    {
                        row += 1;
                    }
                }
                calendarPages.Add(border);
                calendar.AddMonths(1);
                pageNumber += 1;
            }while (calendar.Year < monthYearSelect2.MonthYear.Year ||
                    calendar.Month <= monthYearSelect2.MonthYear.Month);

            printDocument.SetPreviewPageCount(calendarPages.Count, PreviewPageCountType.Final);
        }
Exemplo n.º 17
0
        public void TestNextValidRandom()
        {
            const int numberOfIterations = 10000;

            // Use to allow sequential testing for easier debugging or average timing
            const bool parallel = true;

            Random   random   = new Random();
            Calendar calendar = CultureInfo.CurrentCulture.Calendar;

            Action <int> testAction = iteration =>
            {
                // Random initial DateTime
                int      year          = random.Next(1, 9999);
                int      month         = random.Next(1, 13);
                int      daysInMonth   = calendar.GetDaysInMonth(year, month);
                int      day           = random.Next(1, daysInMonth);
                DateTime startDateTime = new DateTime(
                    year,
                    month,
                    day,
                    random.Next(24),
                    random.Next(60),
                    random.Next(60));

                // Random incrementation
                int      incrementationType = random.Next(5);
                string   incrementationTypeName;
                int      incrementationAmount;
                DateTime expectedDateTime;
                switch (incrementationType)
                {
                default:
                case 0:
                    incrementationTypeName = "Month";
                    incrementationAmount   = random.Next(12 - startDateTime.Month);
                    expectedDateTime       = calendar.AddMonths(
                        startDateTime,
                        incrementationAmount);
                    if (incrementationAmount > 0)
                    {
                        expectedDateTime = new DateTime(
                            expectedDateTime.Year,
                            expectedDateTime.Month,
                            1,
                            0,
                            0,
                            0);
                    }
                    break;

                case 1:
                    incrementationTypeName = "Day";
                    incrementationAmount   = random.Next(daysInMonth - startDateTime.Day);
                    expectedDateTime       = calendar.AddDays(
                        startDateTime,
                        incrementationAmount);
                    if (incrementationAmount > 0)
                    {
                        expectedDateTime = new DateTime(
                            expectedDateTime.Year,
                            expectedDateTime.Month,
                            expectedDateTime.Day,
                            0,
                            0,
                            0);
                    }
                    break;

                case 2:
                    incrementationTypeName = "Hour";
                    incrementationAmount   = random.Next(24 - startDateTime.Hour);
                    expectedDateTime       = calendar.AddHours(
                        startDateTime,
                        incrementationAmount);
                    if (incrementationAmount > 0)
                    {
                        expectedDateTime = new DateTime(
                            expectedDateTime.Year,
                            expectedDateTime.Month,
                            expectedDateTime.Day,
                            expectedDateTime.Hour,
                            0,
                            0);
                    }
                    break;

                case 3:
                    incrementationTypeName = "Minute";
                    incrementationAmount   = random.Next(60 - startDateTime.Minute);
                    expectedDateTime       = calendar.AddMinutes(
                        startDateTime,
                        incrementationAmount);
                    if (incrementationAmount > 0)
                    {
                        expectedDateTime = new DateTime(
                            expectedDateTime.Year,
                            expectedDateTime.Month,
                            expectedDateTime.Day,
                            expectedDateTime.Hour,
                            expectedDateTime.Minute,
                            0);
                    }
                    break;

                case 4:
                    incrementationTypeName = "Second";
                    incrementationAmount   = random.Next(60 - startDateTime.Second);
                    expectedDateTime       = calendar.AddSeconds(
                        startDateTime,
                        incrementationAmount);
                    break;
                }

                // Random week start day
                DayOfWeek weekStartDay;
                string    weekStartDayName;
                switch (random.Next(7))
                {
                default:
                case 0:
                    weekStartDayName = "Monday";
                    weekStartDay     = DayOfWeek.Monday;
                    break;

                case 1:
                    weekStartDayName = "Tuesday";
                    weekStartDay     = DayOfWeek.Tuesday;
                    break;

                case 2:
                    weekStartDayName = "Wednesday";
                    weekStartDay     = DayOfWeek.Wednesday;
                    break;

                case 3:
                    weekStartDayName = "Thursday";
                    weekStartDay     = DayOfWeek.Thursday;
                    break;

                case 4:
                    weekStartDayName = "Friday";
                    weekStartDay     = DayOfWeek.Friday;
                    break;

                case 5:
                    weekStartDayName = "Saturday";
                    weekStartDay     = DayOfWeek.Saturday;
                    break;

                case 6:
                    weekStartDayName = "Sunday";
                    weekStartDay     = DayOfWeek.Sunday;
                    break;
                }

                if (incrementationAmount > 0)
                {
                    // Test
                    DateTime resultantDateTime;
                    switch (incrementationType)
                    {
                    default:
                    case 0:
                        resultantDateTime = startDateTime.NextValid(
                            inclusive: true,
                            firstDayOfWeek:
                            weekStartDay,
                            month:
                            Schedule
                            .Months(
                                startDateTime
                                .Month +
                                incrementationAmount),
                            hour: Hour.Every,
                            minute:
                            Minute.Every,
                            second:
                            Second.Every);
                        break;

                    case 1:
                        resultantDateTime = startDateTime.NextValid(
                            inclusive: true,
                            firstDayOfWeek:
                            weekStartDay,
                            day:
                            Schedule
                            .Days(
                                startDateTime
                                .Day +
                                incrementationAmount),
                            hour: Hour.Every,
                            minute:
                            Minute.Every,
                            second:
                            Second.Every);
                        break;

                    case 2:
                        resultantDateTime = startDateTime.NextValid(
                            inclusive: true,
                            firstDayOfWeek:
                            weekStartDay,
                            hour:
                            Schedule
                            .Hours(
                                startDateTime
                                .Hour +
                                incrementationAmount),
                            minute:
                            Minute.Every,
                            second:
                            Second.Every);
                        break;

                    case 3:
                        resultantDateTime = startDateTime.NextValid(
                            inclusive: true,
                            firstDayOfWeek:
                            weekStartDay,
                            minute:
                            Schedule
                            .Minutes(
                                startDateTime
                                .Minute +
                                incrementationAmount),
                            hour: Hour.Every,
                            second:
                            Second.Every);
                        break;

                    case 4:
                        resultantDateTime = startDateTime.NextValid(
                            inclusive: true,
                            firstDayOfWeek:
                            weekStartDay,
                            hour: Hour.Every,
                            minute:
                            Minute.Every,
                            second:
                            Schedule
                            .Seconds(
                                startDateTime
                                .Second +
                                incrementationAmount));
                        break;
                    }

                    // Report
                    Assert.AreEqual(
                        expectedDateTime,
                        resultantDateTime,
                        string.Format(
                            "Started:<{0}>. Iteration: #{1}, Search: {2} {3} ahead, Week start day: {4}",
                            startDateTime,
                            iteration,
                            incrementationAmount,
                            incrementationAmount > 1
                                ? incrementationTypeName + "s"
                                : incrementationTypeName,
                            weekStartDayName)
                        );
                }
            };

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            if (parallel)
            {
                Parallel.For(0, numberOfIterations, testAction);
            }
            else
            {
                for (int iteration = 0; iteration < numberOfIterations; iteration++)
                {
                    testAction(iteration);
                }
            }
            stopwatch.Stop();

            if (parallel)
            {
                Trace.WriteLine(
                    string.Format(
                        "{0} random iterations took {1}ms",
                        numberOfIterations,
                        stopwatch.ElapsedMilliseconds));
            }
            else
            {
                Trace.WriteLine(
                    string.Format(
                        "{0} random iterations took {1}ms (~{2}ms per iteration)",
                        numberOfIterations,
                        stopwatch.ElapsedMilliseconds,
                        stopwatch.ElapsedMilliseconds / numberOfIterations));
            }
        }
Exemplo n.º 18
0
 public PersianDateTime AddMonths(int months)
 {
     return(new PersianDateTime(Calendar.AddMonths(this.DateTime, months)));
 }
        private void VerificationHelper(Calendar calendar, DateTime time, int months, DateTime expected)
        {
            DateTime actual = calendar.AddMonths(time, months);

            Assert.Equal(expected, actual);
        }
Exemplo n.º 20
0
        /// <summary>
        /// creates calendar display with default values, if creating current month's calendary.
        /// uses the 2 parameters when going to previous or next month
        /// </summary>
        /// <param name="dayInt">numerical equivalent of current day</param>
        /// <param name="dayStr">string day of the week</param>
        private void CreateCalendar(int dayInt = -1, string dayStr = "")
        {
            string month = "";

            if (setMonth == "")
            {
                month = cal.MonthAsSoloString();
            }
            else
            {
                Dictionary <string, int> daysDict = new Dictionary <string, int>()
                {
                    { "January", 1 },
                    { "February", 2 },
                    { "March", 3 },
                    { "April", 4 },
                    { "May", 5 },
                    { "June", 6 },
                    { "July", 7 },
                    { "August", 8 },
                    { "September", 9 },
                    { "October", 10 },
                    { "November", 11 },
                    { "December", 12 },
                };

                cal.Month = daysDict[setMonth];
                month     = setMonth;
            }

            //get previous month's last day
            cal.AddMonths(-1);
            string lastDayofPrevMonth = cal.LastDayInThisMonth.ToString();

            cal.AddMonths(1);

            string lastDayofThisMonth = cal.LastDayInThisMonth.ToString();

            //JanMonth.Text = cal.Month.ToString();

            //TestPrintOut.Text = cal.DayOfWeekAsString(7).ToString();
            string year;

            if (setYear == "")
            {
                year = cal.YearAsString();
            }
            else
            {
                year     = setYear;
                cal.Year = Int32.Parse(setYear);
            }

            DisplayMonthYear.Text = month + " " + year;

            int numDay = 0;

            if (dayInt == -1)
            {
                numDay = Int32.Parse(cal.DayAsString());
            }
            else
            {
                numDay = dayInt;
            }

            string strDay = "";

            if (dayStr == "")
            {
                strDay = cal.DayOfWeekAsSoloString();
            }
            else
            {
                strDay = dayStr;
            }

            //ResultText.Text = year;
            //TokenInfoText.Text = month;

            //get index for first of the month
            int  tmp         = 0;
            bool greaterThan = false;

            if (strDay == "Sunday")
            {
                if (numDay > 0)
                {
                    greaterThan = true;
                    tmp         = numDay - 0;
                }
                else
                {
                    tmp = 0 - (numDay - 1);
                }
            }
            else if (strDay == "Monday")
            {
                if (numDay > 1)
                {
                    greaterThan = true;
                    tmp         = numDay - 1;
                }
                else
                {
                    tmp = 1 - (numDay - 1);
                }
            }
            else if (strDay == "Tuesday")
            {
                if (numDay > 2)
                {
                    greaterThan = true;
                    tmp         = numDay - 2;
                }
                else
                {
                    tmp = 2 - (numDay - 1);
                }
            }
            else if (strDay == "Wednesday")
            {
                if (numDay > 3)
                {
                    greaterThan = true;
                    tmp         = numDay - 3;
                }
                else
                {
                    tmp = 3 - (numDay - 1);
                }
            }
            else if (strDay == "Thursday")
            {
                if (numDay > 4)
                {
                    greaterThan = true;
                    tmp         = numDay - 4;
                }
                else
                {
                    tmp = 4 - (numDay - 1);
                }
            }
            else if (strDay == "Friday")
            {
                if (numDay > 5)
                {
                    greaterThan = true;
                    tmp         = numDay - 5;
                }
                else
                {
                    tmp = 5 - (numDay - 1);
                }
            }
            else if (strDay == "Saturday")
            {
                if (numDay > 6)
                {
                    greaterThan = true;
                    tmp         = numDay - 6;
                }
                else
                {
                    tmp = 6 - (numDay - 1);
                }
            }
            else
            {
                tmp = numDay;
            }

            if (greaterThan)
            {
                tmp = (tmp % 7) - 7;
                tmp = (tmp * (-1) + 1) % 7;
            }

            TextBlock[] textBlkArr = { row0Col0, row0Col1, row0Col2, row0Col3, row0Col4, row0Col5, row0Col6,
                                       row1Col0, row1Col1, row1Col2, row1Col3, row1Col4, row1Col5, row1Col6,
                                       row2Col0, row2Col1, row2Col2, row2Col3, row2Col4, row2Col5, row2Col6,
                                       row3Col0, row3Col1, row3Col2, row3Col3, row3Col4, row3Col5, row3Col6,
                                       row4Col0, row4Col1, row4Col2, row4Col3, row4Col4, row4Col5, row4Col6,
                                       row5Col0, row5Col1, row5Col2, row5Col3, row5Col4, row5Col5, row5Col6 };

            UInt16 startingInt = 0;

            //find out which part of the grid month starts on
            if (tmp == 0)
            {
                textBlkArr[0].Text = "1";
                startingInt        = 0;
            }
            else if (tmp == 1)
            {
                textBlkArr[1].Text = "1";
                startingInt        = 1;
            }
            else if (tmp == 2)
            {
                textBlkArr[2].Text = "1";
                startingInt        = 2;
            }
            else if (tmp == 3)
            {
                textBlkArr[3].Text = "1";
                startingInt        = 3;
            }
            else if (tmp == 4)
            {
                textBlkArr[4].Text = "1";
                startingInt        = 4;
            }
            else if (tmp == 5)
            {
                textBlkArr[5].Text = "1";
                startingInt        = 5;
            }
            else if (tmp == 6)
            {
                textBlkArr[6].Text = "1";
                startingInt        = 6;
            }

            //fill previous month's numerical days and make number look gray
            for (int i = startingInt; i > 0; i--)
            {
                textBlkArr[i - 1].Text       = (Int32.Parse(lastDayofPrevMonth) - (startingInt - i)).ToString();
                textBlkArr[i - 1].Foreground = new SolidColorBrush(Colors.Gray);
            }

            //fill rest of current month's days
            int monthLastDay = Int32.Parse(lastDayofThisMonth);
            int upperIndex   = monthLastDay + startingInt;

            for (int i = startingInt; i < upperIndex; i++)
            {
                textBlkArr[i].Text = (i - startingInt + 1).ToString();
            }

            //fill remaining spaces with following month's days and make number look gray
            for (int i = upperIndex; i != 42; i++)
            {
                textBlkArr[i].Text       = (i - upperIndex + 1).ToString();
                textBlkArr[i].Foreground = new SolidColorBrush(Colors.Gray);
            }
        }
Exemplo n.º 21
0
 /// <summary>
 /// Add the month component.
 /// </summary>
 public void addMonth(int month)
 {
     _date = calendar.AddMonths(_date, month);
     loadMonth();
 }
Exemplo n.º 22
0
 public HijriDate AddMonths(int months)
 {
     return(new HijriDate(Calendar.AddMonths(this.DateTime, months)));
 }
Exemplo n.º 23
0
        /// <summary>Returns a <see langword="Date" /> value representing a specified year, month, and day, with the time information set to midnight (00:00:00).</summary>
        /// <param name="Year">Required. <see langword="Integer" /> expression from 1 through 9999. However, values below this range are also accepted. If <paramref name="Year" /> is 0 through 99, it is interpreted as being between 1930 and 2029, as explained in the "Remarks" section below. If <paramref name="Year" /> is less than 1, it is subtracted from the current year.</param>
        /// <param name="Month">Required. <see langword="Integer" /> expression from 1 through 12. However, values outside this range are also accepted. The value of <paramref name="Month" /> is offset by 1 and applied to January of the calculated year. In other words, (<paramref name="Month" /> - 1) is added to January. The year is recalculated if necessary. The following results illustrate this effect:If <paramref name="Month" /> is 1, the result is January of the calculated year.If <paramref name="Month" /> is 0, the result is December of the previous year.If <paramref name="Month" /> is -1, the result is November of the previous year.If <paramref name="Month" /> is 13, the result is January of the following year.</param>
        /// <param name="Day">Required. <see langword="Integer" /> expression from 1 through 31. However, values outside this range are also accepted. The value of <paramref name="Day" /> is offset by 1 and applied to the first day of the calculated month. In other words, (<paramref name="Day" /> - 1) is added to the first of the month. The month and year are recalculated if necessary. The following results illustrate this effect:If <paramref name="Day" /> is 1, the result is the first day of the calculated month.If <paramref name="Day" /> is 0, the result is the last day of the previous month.If <paramref name="Day" /> is -1, the result is the penultimate day of the previous month.If <paramref name="Day" /> is past the end of the current month, the result is the appropriate day of the following month. For example, if <paramref name="Month" /> is 4 and <paramref name="Day" /> is 31, the result is May 1.</param>
        /// <returns>Returns a <see langword="Date" /> value representing a specified year, month, and day, with the time information set to midnight (00:00:00).</returns>
        public static DateTime DateSerial(int Year, int Month, int Day)
        {
            Calendar currentCalendar = DateAndTime.CurrentCalendar;

            if (Year < 0)
            {
                Year = checked (currentCalendar.GetYear(DateTime.Today) + Year);
            }
            else if (Year < 100)
            {
                Year = currentCalendar.ToFourDigitYear(Year);
            }
            if (currentCalendar is GregorianCalendar)
            {
                if (Month >= 1)
                {
                    if (Month <= 12)
                    {
                        if (Day >= 1)
                        {
                            if (Day <= 28)
                            {
                                return(new DateTime(Year, Month, Day));
                            }
                        }
                    }
                }
            }
            DateTime dateTime;

            try
            {
                dateTime = currentCalendar.ToDateTime(Year, 1, 1, 0, 0, 0, 0);
            }
            catch (StackOverflowException ex)
            {
                throw ex;
            }
            catch (OutOfMemoryException ex)
            {
                throw ex;
            }
            catch (ThreadAbortException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw ExceptionUtils.VbMakeException((Exception) new ArgumentException(Utils.GetResourceString("Argument_InvalidValue1", new string[1]
                {
                    nameof(Year)
                })), 5);
            }
            DateTime time;

            try
            {
                time = currentCalendar.AddMonths(dateTime, checked (Month - 1));
            }
            catch (StackOverflowException ex)
            {
                throw ex;
            }
            catch (OutOfMemoryException ex)
            {
                throw ex;
            }
            catch (ThreadAbortException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw ExceptionUtils.VbMakeException((Exception) new ArgumentException(Utils.GetResourceString("Argument_InvalidValue1", new string[1]
                {
                    nameof(Month)
                })), 5);
            }
            try
            {
                return(currentCalendar.AddDays(time, checked (Day - 1)));
            }
            catch (StackOverflowException ex)
            {
                throw ex;
            }
            catch (OutOfMemoryException ex)
            {
                throw ex;
            }
            catch (ThreadAbortException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw ExceptionUtils.VbMakeException((Exception) new ArgumentException(Utils.GetResourceString("Argument_InvalidValue1", new string[1]
                {
                    nameof(Day)
                })), 5);
            }
        }
Exemplo n.º 24
0
        public static DateTime DateSerial(int Year, int Month, int Day)
        {
            DateTime time2;
            Calendar currentCalendar = CurrentCalendar;

            if (Year < 0)
            {
                Year = currentCalendar.GetYear(DateTime.Today) + Year;
            }
            else if (Year < 100)
            {
                Year = currentCalendar.ToFourDigitYear(Year);
            }
            if ((((currentCalendar is GregorianCalendar) && (Month >= 1)) && ((Month <= 12) && (Day >= 1))) && (Day <= 0x1c))
            {
                return(new DateTime(Year, Month, Day));
            }
            try
            {
                time2 = currentCalendar.ToDateTime(Year, 1, 1, 0, 0, 0, 0);
            }
            catch (StackOverflowException exception)
            {
                throw exception;
            }
            catch (OutOfMemoryException exception2)
            {
                throw exception2;
            }
            catch (ThreadAbortException exception3)
            {
                throw exception3;
            }
            catch (Exception)
            {
                throw ExceptionUtils.VbMakeException(new ArgumentException(Utils.GetResourceString("Argument_InvalidValue1", new string[] { "Year" })), 5);
            }
            try
            {
                time2 = currentCalendar.AddMonths(time2, Month - 1);
            }
            catch (StackOverflowException exception4)
            {
                throw exception4;
            }
            catch (OutOfMemoryException exception5)
            {
                throw exception5;
            }
            catch (ThreadAbortException exception6)
            {
                throw exception6;
            }
            catch (Exception)
            {
                throw ExceptionUtils.VbMakeException(new ArgumentException(Utils.GetResourceString("Argument_InvalidValue1", new string[] { "Month" })), 5);
            }
            try
            {
                time2 = currentCalendar.AddDays(time2, Day - 1);
            }
            catch (StackOverflowException exception7)
            {
                throw exception7;
            }
            catch (OutOfMemoryException exception8)
            {
                throw exception8;
            }
            catch (ThreadAbortException exception9)
            {
                throw exception9;
            }
            catch (Exception)
            {
                throw ExceptionUtils.VbMakeException(new ArgumentException(Utils.GetResourceString("Argument_InvalidValue1", new string[] { "Day" })), 5);
            }
            return(time2);
        }
Exemplo n.º 25
0
        public static void AddMonths_Invalid(Calendar calendar)
        {
            Assert.ThrowsAny<ArgumentException>(() => calendar.AddMonths(calendar.MaxSupportedDateTime, 1));
            Assert.ThrowsAny<ArgumentException>(() => calendar.AddMonths(calendar.MinSupportedDateTime, -1)); // JapaneseCalendar throws ArgumentException

            Assert.Throws<ArgumentOutOfRangeException>("months", () => calendar.AddMonths(DateTime.Now, -120001));
            Assert.Throws<ArgumentOutOfRangeException>("months", () => calendar.AddMonths(DateTime.Now, 120001));
        }