Beispiel #1
0
        public void AddMinutes_Invalid_ThrowsArgumentException()
        {
            Calendar calendar = Calendar;

            AssertExtensions.Throws <ArgumentException>(null, () => calendar.AddMinutes(calendar.MaxSupportedDateTime, 1));
            AssertExtensions.Throws <ArgumentException>(null, () => calendar.AddMinutes(calendar.MinSupportedDateTime, -1));
        }
Beispiel #2
0
    public void TestCalendarAddMinutes()
    {
        long     multiplier = TimeSpan.TicksPerMinute;
        DateTime time       = DateTime.Now;

        TimeSpan ts = calendar.AddMinutes(time, -3) - time;

        AssertEquals("AddMinutes (1)", multiplier * -3, ts.Ticks);

        ts = calendar.AddMinutes(time, 0) - time;
        AssertEquals("AddMinutes (2)", multiplier * 0, ts.Ticks);

        ts = calendar.AddMinutes(time, 145) - time;
        AssertEquals("AddMinutes (3)", multiplier * 145, ts.Ticks);
    }
Beispiel #3
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);
    }
Beispiel #4
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");
                }
            }
        }
Beispiel #5
0
   private static void AddMinutes(Calendar cal)
   {
      int minutes = 90;
      Example.time = date1;

      // <Snippet4>
      returnTime = DateTime.SpecifyKind(cal.AddMinutes(time, minutes), time.Kind);
      // </Snippet4>
      Console.WriteLine(returnTime.Kind == time.Kind);
   }
        private DateTime quitaHrsDeFecha(DateTime fecha)
        {
            Calendar myCal = CultureInfo.InvariantCulture.Calendar;

            fecha = myCal.AddHours(fecha, 0);
            fecha = myCal.AddMinutes(fecha, 0);
            fecha = myCal.AddSeconds(fecha, 0);
            fecha = myCal.AddMilliseconds(fecha, 0);

            return(fecha);
        }
        public virtual Calendar normalizeCalendar(Calendar cal, XSDuration timezone)
        {
            Calendar adjusted = (Calendar)cal.clone();

            if (timezone != null)
            {
                int hours   = timezone.hours();
                int minutes = timezone.minutes();
                if (!timezone.negative())
                {
                    hours   *= -1;
                    minutes *= -1;
                }
                adjusted.AddHours(hours);
                adjusted.AddMinutes(minutes);
            }

            return(adjusted);
        }
Beispiel #8
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();
        }
Beispiel #9
0
        //Метод вывода времени прибытия автобуса
        private static void Output(decimal dt, string strdt, decimal j, string NameBus)
        {
            //Время сейчас
            int     WholeNow   = Convert.ToInt32(Math.Truncate(dt));
            decimal decimalNow = (dt - WholeNow);

            strdt = Convert.ToString(decimalNow);
            char[] delete = { ',' };
            foreach (char c in delete)
            {
                strdt = strdt.Replace(c.ToString(), "");
            }
            strdt = strdt.Remove(0, 1);
            int      DecimalNow = Convert.ToInt32(strdt);
            DateTime dtNow      = new DateTime(0001, 01, 01, new GregorianCalendar());
            Calendar myCal      = CultureInfo.InvariantCulture.Calendar;

            dtNow = myCal.AddHours(dtNow, WholeNow);
            dtNow = myCal.AddMinutes(dtNow, DecimalNow);

            //Время прибытия
            int     WholeThen   = Convert.ToInt32(Math.Truncate(j));
            decimal decimalThen = (j - WholeThen);

            strdt = Convert.ToString(decimalThen);
            foreach (char c in delete)
            {
                strdt = strdt.Replace(c.ToString(), "");
            }
            strdt = strdt.Remove(0, 1);
            int      DecimalThen = Convert.ToInt32(strdt);
            DateTime dtThen      = new DateTime(0001, 01, 01, new GregorianCalendar());
            Calendar myCalThen   = CultureInfo.InvariantCulture.Calendar;

            dtThen = myCalThen.AddHours(dtThen, WholeThen);
            dtThen = myCalThen.AddMinutes(dtThen, DecimalThen);

            Console.WriteLine(NameBus + dtThen.Subtract(dtNow) + " до прибытия.");
        }
Beispiel #10
0
 public static void AddMinutes_Invalid(Calendar calendar)
 {
     Assert.Throws <ArgumentException>(() => calendar.AddMinutes(calendar.MaxSupportedDateTime, 1));
     Assert.Throws <ArgumentException>(() => calendar.AddMinutes(calendar.MinSupportedDateTime, -1));
 }
Beispiel #11
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));
            }
        }
        /// <summary>
        /// Invoked when 'Get History' button is clicked.
        /// Depending on the user selection, this handler uses one of the overloaded
        /// 'GetSystemHistoryAsync' APIs to retrieve the pedometer history of the user
        /// </summary>
        /// <param name="sender">unused</param>
        /// <param name="e">unused</param>
        async private void GetHistory_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            IReadOnlyList <PedometerReading> historyReadings = null;
            DateTimeFormatter timestampFormatter             = new DateTimeFormatter("shortdate longtime");

            // Disable subsequent history retrieval while the async operation is in progress
            GetHistory.IsEnabled = false;

            // clear previous content being displayed
            historyRecords.Clear();

            try
            {
                if (getAllHistory)
                {
                    DateTime       dt            = DateTime.FromFileTimeUtc(0);
                    DateTimeOffset fromBeginning = new DateTimeOffset(dt);
                    rootPage.NotifyUser("Retrieving all available History", NotifyType.StatusMessage);
                    historyReadings = await Pedometer.GetSystemHistoryAsync(fromBeginning);
                }
                else
                {
                    String   notificationString = "Retrieving history from: ";
                    Calendar calendar           = new Calendar();
                    calendar.ChangeClock("24HourClock");

                    // DateTime picker will also include hour, minute and seconds from the the system time.
                    // Decrement the same to be able to correctly add TimePicker values.

                    calendar.SetDateTime(FromDate.Date);
                    calendar.AddNanoseconds(-calendar.Nanosecond);
                    calendar.AddSeconds(-calendar.Second);
                    calendar.AddMinutes(-calendar.Minute);
                    calendar.AddHours(-calendar.Hour);
                    calendar.AddSeconds(Convert.ToInt32(FromTime.Time.TotalSeconds));

                    DateTimeOffset fromTime = calendar.GetDateTime();

                    calendar.SetDateTime(ToDate.Date);
                    calendar.AddNanoseconds(-calendar.Nanosecond);
                    calendar.AddSeconds(-calendar.Second);
                    calendar.AddMinutes(-calendar.Minute);
                    calendar.AddHours(-calendar.Hour);
                    calendar.AddSeconds(Convert.ToInt32(ToTime.Time.TotalSeconds));

                    DateTimeOffset toTime = calendar.GetDateTime();

                    notificationString += timestampFormatter.Format(fromTime);
                    notificationString += " To ";
                    notificationString += timestampFormatter.Format(toTime);

                    if (toTime.ToFileTime() < fromTime.ToFileTime())
                    {
                        rootPage.NotifyUser("Invalid time span. 'To Time' must be equal or more than 'From Time'", NotifyType.ErrorMessage);

                        // Enable subsequent history retrieval while the async operation is in progress
                        GetHistory.IsEnabled = true;
                    }
                    else
                    {
                        TimeSpan span;
                        span = TimeSpan.FromTicks(toTime.Ticks - fromTime.Ticks);
                        rootPage.NotifyUser(notificationString, NotifyType.StatusMessage);
                        historyReadings = await Pedometer.GetSystemHistoryAsync(fromTime, span);
                    }
                }

                if (historyReadings != null)
                {
                    foreach (PedometerReading reading in historyReadings)
                    {
                        HistoryRecord record = new HistoryRecord(reading);
                        historyRecords.Add(record);
                    }

                    rootPage.NotifyUser("History retrieval completed", NotifyType.StatusMessage);
                }
            }
            catch (UnauthorizedAccessException)
            {
                rootPage.NotifyUser("User has denied access to activity history", NotifyType.ErrorMessage);
            }

            // Finally, re-enable history retrieval
            GetHistory.IsEnabled = true;
        }
Beispiel #13
0
 public static void AddMinutes_Invalid(Calendar calendar)
 {
     Assert.Throws<ArgumentException>(() => calendar.AddMinutes(calendar.MaxSupportedDateTime, 1));
     Assert.Throws<ArgumentException>(() => calendar.AddMinutes(calendar.MinSupportedDateTime, -1));
 }
Beispiel #14
0
        /// <summary>
        /// Invoked when 'Get History' button is clicked.
        /// Depending on the user selection, this handler uses one of the overloaded
        /// 'GetSystemHistoryAsync' APIs to retrieve the pedometer history of the user
        /// </summary>
        /// <param name="sender">unused</param>
        /// <param name="e">unused</param>
        async private void GetHistory_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            GetHistory.IsEnabled = false;

            // Determine if we can access pedometers
            var deviceAccessInfo = DeviceAccessInformation.CreateFromDeviceClassId(PedometerClassId);

            if (deviceAccessInfo.CurrentStatus == DeviceAccessStatus.Allowed)
            {
                // Determine if a pedometer is present
                // This can also be done using Windows::Devices::Enumeration::DeviceInformation::FindAllAsync
                var sensor = await Pedometer.GetDefaultAsync();

                if (sensor != null)
                {
                    IReadOnlyList <PedometerReading> historyReadings = null;
                    var timestampFormatter = new DateTimeFormatter("shortdate longtime");

                    // Disable subsequent history retrieval while the async operation is in progress
                    GetHistory.IsEnabled = false;

                    // clear previous content being displayed
                    historyRecords.Clear();

                    try
                    {
                        if (getAllHistory)
                        {
                            var dt            = DateTime.FromFileTimeUtc(0);
                            var fromBeginning = new DateTimeOffset(dt);
                            rootPage.NotifyUser("Retrieving all available History", NotifyType.StatusMessage);
                            historyReadings = await Pedometer.GetSystemHistoryAsync(fromBeginning);
                        }
                        else
                        {
                            String notificationString = "Retrieving history from: ";
                            var    calendar           = new Calendar();
                            calendar.ChangeClock("24HourClock");

                            // DateTime picker will also include hour, minute and seconds from the the system time.
                            // Decrement the same to be able to correctly add TimePicker values.

                            calendar.SetDateTime(FromDate.Date);
                            calendar.AddNanoseconds(-calendar.Nanosecond);
                            calendar.AddSeconds(-calendar.Second);
                            calendar.AddMinutes(-calendar.Minute);
                            calendar.AddHours(-calendar.Hour);
                            calendar.AddSeconds(Convert.ToInt32(FromTime.Time.TotalSeconds));

                            DateTimeOffset fromTime = calendar.GetDateTime();

                            calendar.SetDateTime(ToDate.Date);
                            calendar.AddNanoseconds(-calendar.Nanosecond);
                            calendar.AddSeconds(-calendar.Second);
                            calendar.AddMinutes(-calendar.Minute);
                            calendar.AddHours(-calendar.Hour);
                            calendar.AddSeconds(Convert.ToInt32(ToTime.Time.TotalSeconds));

                            DateTimeOffset toTime = calendar.GetDateTime();

                            notificationString += timestampFormatter.Format(fromTime);
                            notificationString += " To ";
                            notificationString += timestampFormatter.Format(toTime);

                            if (toTime.ToFileTime() < fromTime.ToFileTime())
                            {
                                rootPage.NotifyUser("Invalid time span. 'To Time' must be equal or more than 'From Time'", NotifyType.ErrorMessage);

                                // Enable subsequent history retrieval while the async operation is in progress
                                GetHistory.IsEnabled = true;
                            }
                            else
                            {
                                TimeSpan span = TimeSpan.FromTicks(toTime.Ticks - fromTime.Ticks);
                                rootPage.NotifyUser(notificationString, NotifyType.StatusMessage);
                                historyReadings = await Pedometer.GetSystemHistoryAsync(fromTime, span);
                            }
                        }

                        if (historyReadings != null)
                        {
                            foreach (PedometerReading reading in historyReadings)
                            {
                                HistoryRecord record = new HistoryRecord(reading);
                                historyRecords.Add(record);

                                // Get at most 100 records (number is arbitrary chosen for demonstration purposes)
                                if (historyRecords.Count == 100)
                                {
                                    break;
                                }
                            }

                            rootPage.NotifyUser("History retrieval completed", NotifyType.StatusMessage);
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {
                        rootPage.NotifyUser("User has denied access to activity history", NotifyType.ErrorMessage);
                    }

                    // Finally, re-enable history retrieval
                    GetHistory.IsEnabled = true;
                }
                else
                {
                    rootPage.NotifyUser("No pedometers found", NotifyType.ErrorMessage);
                }
            }
            else
            {
                rootPage.NotifyUser("Access to pedometers is denied", NotifyType.ErrorMessage);
            }
        }