Inheritance: ICalendar
        /// <summary>
        /// This is the click handler for the 'Get Activity History' button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        async private void ScenarioGetActivityHistory(object sender, RoutedEventArgs e)
        {
            // Reset fields and status
            ScenarioOutput_Count.Text = "No data";
            ScenarioOutput_Activity1.Text = "No data";
            ScenarioOutput_Confidence1.Text = "No data";
            ScenarioOutput_Timestamp1.Text = "No data";
            ScenarioOutput_ActivityN.Text = "No data";
            ScenarioOutput_ConfidenceN.Text = "No data";
            ScenarioOutput_TimestampN.Text = "No data";
            rootPage.NotifyUser("", NotifyType.StatusMessage);

            var calendar = new Calendar();
            calendar.SetToNow();
            calendar.AddDays(-1);
            var yesterday = calendar.GetDateTime();

            // Get history from yesterday onwards
            var history = await ActivitySensor.GetSystemHistoryAsync(yesterday);

            ScenarioOutput_Count.Text = history.Count.ToString();
            if (history.Count > 0)
            {
                var reading1 = history[0];
                ScenarioOutput_Activity1.Text = reading1.Activity.ToString();
                ScenarioOutput_Confidence1.Text = reading1.Confidence.ToString();
                ScenarioOutput_Timestamp1.Text = reading1.Timestamp.ToString("u");

                var readingN = history[history.Count - 1];
                ScenarioOutput_ActivityN.Text = readingN.Activity.ToString();
                ScenarioOutput_ConfidenceN.Text = readingN.Confidence.ToString();
                ScenarioOutput_TimestampN.Text = readingN.Timestamp.ToString("u");
            }
        }
        /// <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 uses the Windows.Globalization.Calendar class to display the parts of a date.

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

            // Create Calendar objects using different Unicode extensions for different languages.
            // NOTE: Calendar (ca) and numeral system (nu) are the only supported extensions with any others being ignored 
            // (note that collation (co) extension is ignored in the last example).
            Calendar cal1 = new Calendar();
            Calendar cal2 = new Calendar(new[] { "ar-SA-u-ca-gregory-nu-Latn" });
            Calendar cal3 = new Calendar(new[] { "he-IL-u-nu-arab" });
            Calendar cal4 = new Calendar(new[] { "he-IL-u-ca-hebrew-co-phonebk" });

            // Display individual date/time elements.
            results.AppendLine("User's default Calendar object : ");
            results.AppendLine(GetCalendarProperties(cal1));

            results.AppendLine("Calendar object with Arabic language, Gregorian Calendar and Latin Numeral System (ar-SA-ca-gregory-nu-Latn) :");
            results.AppendLine(GetCalendarProperties(cal2));

            results.AppendLine("Calendar object with Hebrew language, Default Calendar for that language and Arab Numeral System (he-IL-u-nu-arab) :");
            results.AppendLine(GetCalendarProperties(cal3));

            results.AppendLine("Calendar object with Hebrew language, Hebrew Calendar, Default Numeral System for that language and Phonebook collation (he-IL-u-ca-hebrew-co-phonebk) :");
            results.AppendLine(GetCalendarProperties(cal4));

            // Display the results
            OutputTextBlock.Text = results.ToString();
        }
        /// <summary>
        /// This is the click handler for the 'combine' button.  The values of the TimePicker and DatePicker are combined into a single DateTimeOffset.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void combine_Click(object sender, RoutedEventArgs e)
        {
            DateTimeFormatter dateFormatter = new DateTimeFormatter("shortdate");
            DateTimeFormatter timeFormatter = new DateTimeFormatter("shorttime");

            // We use a calendar to determine daylight savings time transition days
            Calendar calendar = new Calendar();
            calendar.ChangeClock("24HourClock");

            // The value of the selected time in a TimePicker is stored as a TimeSpan, so it is possible to add it directly to the value of the selected date
            DateTimeOffset selectedDate = this.datePicker.Date;
            DateTimeOffset combinedValue = new DateTimeOffset(new DateTime(selectedDate.Year, selectedDate.Month, selectedDate.Day) + this.timePicker.Time);

            calendar.SetDateTime(combinedValue);

            // If the day does not have 24 hours, then the user has selected a day in which a Daylight Savings Time transition occurs.
            //    It is the app developer's responsibility for validating the combination of the date and time values.
            if (calendar.NumberOfHoursInThisPeriod != 24)
            {
                rootPage.NotifyUser("You selected a DST transition day", NotifyType.StatusMessage);
            }
            else
            {
                rootPage.NotifyUser("Combined value: " + dateFormatter.Format(combinedValue) + " " + timeFormatter.Format(combinedValue), NotifyType.StatusMessage);
            }
        }
        /// <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 uses the Windows.Globalization.Calendar class to display the parts of a date.

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

            // Create Calendar objects using different constructors.
            Calendar calendar = new Calendar();
            Calendar japaneseCalendar = new Calendar(new[] { "ja-JP" }, CalendarIdentifiers.Japanese, ClockIdentifiers.TwelveHour);
            Calendar hebrewCalendar = new Calendar(new[] { "he-IL" }, CalendarIdentifiers.Hebrew, ClockIdentifiers.TwentyFourHour);

            // Display individual date/time elements.
            results.AppendLine("User's default calendar system: " + calendar.GetCalendarSystem());
            results.AppendLine("Name of Month: " + calendar.MonthAsSoloString());
            results.AppendLine("Day of Month: " + calendar.DayAsPaddedString(2));
            results.AppendLine("Day of Week: " + calendar.DayOfWeekAsSoloString());
            results.AppendLine("Year: " + calendar.YearAsString());
            results.AppendLine();
            results.AppendLine("Calendar system: " + japaneseCalendar.GetCalendarSystem());
            results.AppendLine("Name of Month: " + japaneseCalendar.MonthAsSoloString());
            results.AppendLine("Day of Month: " + japaneseCalendar.DayAsPaddedString(2));
            results.AppendLine("Day of Week: " + japaneseCalendar.DayOfWeekAsSoloString());
            results.AppendLine("Year: " + japaneseCalendar.YearAsString());
            results.AppendLine();
            results.AppendLine("Calendar system: " + hebrewCalendar.GetCalendarSystem());
            results.AppendLine("Name of Month: " + hebrewCalendar.MonthAsSoloString());
            results.AppendLine("Day of Month: " + hebrewCalendar.DayAsPaddedString(2));
            results.AppendLine("Day of Week: " + hebrewCalendar.DayOfWeekAsSoloString());
            results.AppendLine("Year: " + hebrewCalendar.YearAsString());
            results.AppendLine();

            // Display the results
            OutputTextBlock.Text=results.ToString();
        }
 public void AddDurationToDate(Calendar calendar)
 {
     if (isPositive)
     {
         calendar.Year += GetValue(years);//.set(Calendar.YEAR, calendar.get(Calendar.YEAR) + GetValue(years));
         calendar.Month += GetValue(months);//.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + getValue(months));
         calendar.Day += GetValue(days);//.set(Calendar.WEEK_OF_YEAR,calendar.get(Calendar.WEEK_OF_YEAR) + getValue(weeks));
         //calendar.set(Calendar.DAY_OF_MONTH,
         //        calendar.get(Calendar.DAY_OF_MONTH) + getValue(days));
         calendar.Hour += GetValue(hours);//.set(Calendar.HOUR_OF_DAY,calendar.get(Calendar.HOUR_OF_DAY) + getValue(hours));
         calendar.Minute += GetValue(minutes);//.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE) + getValue(minutes));
         calendar.Second += GetValue(seconds);//.set(Calendar.SECOND, calendar.get(Calendar.SECOND) + getValue(seconds));
     }
     else
     {
         calendar.Year -= GetValue(years);//.set(Calendar.YEAR, calendar.get(Calendar.YEAR) + GetValue(years));
         calendar.Month -= GetValue(months);//.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + getValue(months));
         calendar.Day -= GetValue(days);//.set(Calendar.WEEK_OF_YEAR,calendar.get(Calendar.WEEK_OF_YEAR) + getValue(weeks));
         //calendar.set(Calendar.DAY_OF_MONTH,
         //        calendar.get(Calendar.DAY_OF_MONTH) + getValue(days));
         calendar.Hour -= GetValue(hours);//.set(Calendar.HOUR_OF_DAY,calendar.get(Calendar.HOUR_OF_DAY) + getValue(hours));
         calendar.Minute -= GetValue(minutes);//.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE) + getValue(minutes));
         calendar.Second -= GetValue(seconds);//.set(Calendar.SECOND, calendar.get(Calendar.SECOND) + getValue(seconds));
     }
 }
Example #6
0
        public void TestCalendarLimits(string calendar)
        {
            using var _ = new AssertionScope();

            var sut = new WG.Calendar(new [] { "en" }, WG.CalendarIdentifiers.Japanese, "24HourClock");

            sut.SetToMin();
            CheckLimits($"Min");

            sut.SetToMax();
            CheckLimits($"Max");

            sut.SetToNow();
            CheckLimits($"Max");

            void CheckLimits(string context)
            {
                // Following tests are just to ensure no exceptions are raised
                // by asking those values
                sut.NumberOfEras.Should().BePositive(context);
                sut.Era.Should().BePositive(context);
                sut.FirstMonthInThisYear.Should().BePositive(context);
                sut.NumberOfDaysInThisMonth.Should().BePositive(context);
                sut.DayOfWeek.Should().NotBeNull(context);
                sut.NumberOfEras.Should().BePositive(context);
                sut.FirstEra.Should().BePositive(context);
                sut.LastEra.Should().BePositive(context);
                sut.Period.Should().BePositive(context);
                sut.ResolvedLanguage.Should().NotBeEmpty(context);
            }
        }
Example #7
0
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.
        /// This parameter is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // TODO: Prepare page for display here.

            // TODO: If your application contains multiple pages, ensure that 
            // you are handling the hardware Back button by registering for the
            // Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
            // If you are using the NavigationHelper provided by some templates,
            // this event is handled for you.
            FBSession sess = FBSession.ActiveSession;

            if (sess.LoggedIn)
            {
                LoginButton.Content = "Logout";
                Calendar cal = new Calendar();
                cal.SetDateTime(sess.AccessTokenData.ExpirationDate);

                ResponseText.Text = sess.AccessTokenData.AccessToken;

                ExpirationDate.Text = cal.DayOfWeekAsString() + "," +
                    cal.YearAsString() + "/" + cal.MonthAsNumericString() +
                    "/" + cal.DayAsString() + ", " + cal.HourAsPaddedString(2) +
                    ":" + cal.MinuteAsPaddedString(2) + ":" +
                    cal.SecondAsPaddedString(2);
            }
            else
            {
                App.InitializeFBSession();
            }
        }
Example #8
0
 private static DateTime InitRepeatStartDate(String repeatFrom, DateTime completedTime, DateTime dueDate, Calendar taskCal)
 {
     if (IsRepeatFromCompleteTime(repeatFrom, completedTime))
     {
         taskCal.Year = completedTime.Year;
         taskCal.Month = completedTime.Month;
         taskCal.Day = completedTime.Day;
         taskCal.Hour = dueDate.Hour;
         taskCal.Minute = dueDate.Minute;
         taskCal.Second = dueDate.Second;
         return taskCal.GetDateTime().DateTime;
         //taskCal.SetDateTime(completedTime);//.setTime(completedTime);
         //int year = taskCal.Year;//taskCal.get(Calendar.YEAR);
         //int month = taskCal.Month;//.get(Calendar.MONTH);
         //int day = taskCal.Day;//.get(Calendar.DAY_OF_MONTH);
         //taskCal.SetDateTime(dueDate)//.setTime(dueDate);
         //int hour = taskCal.Hour;//.get(Calendar.HOUR_OF_DAY);
         //int minute = taskCal.Minute;//.get(Calendar.MINUTE);
         //int second = taskCal.Second;//.get(Calendar.SECOND);
         //taskCal.clear();
         //taskCal.(year, month, day, hour, minute, second);
         //return taskCal.getTime();
     }
     return dueDate;
 }
        public Scenario4()
        {
            this.InitializeComponent();

            try
            {
                formatterShortDateLongTime = new DateTimeFormatter("{month.integer}/{day.integer}/{year.full} {hour.integer}:{minute.integer(2)}:{second.integer(2)}", new[] { "en-US" }, "US", Windows.Globalization.CalendarIdentifiers.Gregorian, Windows.Globalization.ClockIdentifiers.TwentyFourHour);
                formatterLongTime = new DateTimeFormatter("{hour.integer}:{minute.integer(2)}:{second.integer(2)}", new[] { "en-US" }, "US", Windows.Globalization.CalendarIdentifiers.Gregorian, Windows.Globalization.ClockIdentifiers.TwentyFourHour);
                calendar = new Calendar();
                decimalFormatter = new DecimalFormatter();
                geofenceCollection = new  ObservableCollection<GeofenceItem>();
                eventCollection = new ObservableCollection<string>();

                // Geofencing setup
                InitializeGeolocation();

                // using data binding to the root page collection of GeofenceItems
                RegisteredGeofenceListBox.DataContext = geofenceCollection;

                // using data binding to the root page collection of GeofenceItems associated with events
                GeofenceEventsListBox.DataContext = eventCollection;

                coreWindow = CoreWindow.GetForCurrentThread(); // this needs to be set before InitializeComponent sets up event registration for app visibility
                coreWindow.VisibilityChanged += OnVisibilityChanged;
            }
            catch (Exception ex)
            {
                // GeofenceMonitor failed in adding a geofence
                // exceptions could be from out of memory, lat/long out of range,
                // too long a name, not a unique name, specifying an activation
                // time + duration that is still in the past
                _rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
            }
        }
Example #10
0
        /// <summary>
        /// Coerces the <paramref name="utcDateTime"/> according to the min and max
        /// allowed values of the <paramref name="calendar"/> parameter.
        /// </summary>
        /// <returns>The coerced value.</returns>
        internal static DateTime CoerceDateTime(DateTime utcDateTime, Windows.Globalization.Calendar calendar)
        {
            var calendarValue = calendar.GetDateTime().UtcDateTime;
            var dateTime      = DateTime.SpecifyKind(utcDateTime, DateTimeKind.Utc);

            calendar.SetToMin();
            calendar.AddDays(1);
            var minValue = calendar.GetDateTime().UtcDateTime.AddDays(-1);

            calendar.SetToMax();
            calendar.AddDays(-1);
            var maxValue = calendar.GetDateTime().UtcDateTime.AddDays(1);

            calendar.SetDateTime(calendarValue);

            if (dateTime < minValue)
            {
                return(DateTime.SpecifyKind(minValue, utcDateTime.Kind));
            }

            if (dateTime > maxValue)
            {
                return(DateTime.SpecifyKind(maxValue, utcDateTime.Kind));
            }

            return(utcDateTime);
        }
        private void ShowResults()
        {
            // 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();
        }
 private string ReportCalendarData(Calendar calendar, string calendarLabel)
 {
     string results = calendarLabel + ": " + calendar.GetCalendarSystem() + "\n";
     results += "Name of Month: " + calendar.MonthAsSoloString() + "\n";
     results += "Day of Month: " + calendar.DayAsPaddedString(2) + "\n";
     results += "Day of Week: " + calendar.DayOfWeekAsSoloString() + "\n";
     results += "Year: " + calendar.YearAsString() + "\n";
     results += "\n";
     return results;
 }
 private string ReportCalendarData(Calendar calendar, string calendarLabel)
 {
     string results = calendarLabel + ": " + calendar.GetCalendarSystem() + "\n";
     results += "Months in this Year: " + calendar.NumberOfMonthsInThisYear + "\n";
     results += "Days in this Month: " + calendar.NumberOfDaysInThisMonth + "\n";
     results += "Hours in this Period: " + calendar.NumberOfHoursInThisPeriod + "\n";
     results += "Era: " + calendar.EraAsString() + "\n";
     results += "\n";
     return results;
 }
Example #14
0
        internal override string GetValueStringForNonGregorianCalendars(Windows.Globalization.Calendar calendar)
        {
            var valueString = string.Format("{0}:{1}", calendar.HourAsPaddedString(2), calendar.MinuteAsPaddedString(2));

            if (calendar.GetClock() == Windows.Globalization.ClockIdentifiers.TwelveHour)
            {
                valueString = string.Format("{0}{1}", valueString, calendar.PeriodAsString());
            }

            return(valueString);
        }
Example #15
0
 public static DateTime? CalculateRemindTime(TickTickDuration duration, long dueTime)
 {
     if (dueTime <= 0 || duration == null)
     {
         return null;
     }
     Calendar calendar = new Calendar();
     //calendar.setTimeInMillis(dueTime); // TODO 有问题
     duration.AddDurationToDate(calendar);
     return DateTimeUtils.ClearSecondOfDay(calendar.GetDateTime().DateTime).Value;
 }
Example #16
0
 /// <summary>
 /// Gets zero based calendar hour.
 /// </summary>
 /// <returns>
 /// Calendar hour. If the calendar clock is 12 hour and the
 /// hour value is 12, then this method will return 0.
 /// </returns>
 internal static int ZeroBasedHour(this Windows.Globalization.Calendar calendar)
 {
     if (calendar.GetClock() == ClockIdentifiers.TwentyFourHour)
     {
         return(calendar.Hour);
     }
     else
     {
         return(calendar.Hour == 12 ? 0 : calendar.Hour);
     }
 }
        /// <summary>
        /// This is the click handler for the 'Get Activity History' button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        async private void ScenarioGetActivityHistory(object sender, RoutedEventArgs e)
        {
            // Reset fields and status
            ScenarioOutput_Count.Text = "No data";
            ScenarioOutput_Activity1.Text = "No data";
            ScenarioOutput_Confidence1.Text = "No data";
            ScenarioOutput_Timestamp1.Text = "No data";
            ScenarioOutput_ActivityN.Text = "No data";
            ScenarioOutput_ConfidenceN.Text = "No data";
            ScenarioOutput_TimestampN.Text = "No data";
            rootPage.NotifyUser("", NotifyType.StatusMessage);

            // Determine if we can access activity sensors
            var deviceAccessInfo = DeviceAccessInformation.CreateFromDeviceClassId(ActivitySensorClassId);
            if (deviceAccessInfo.CurrentStatus == DeviceAccessStatus.Allowed)
            {
                // Determine if an activity sensor is present
                // This can also be done using Windows::Devices::Enumeration::DeviceInformation::FindAllAsync
                var activitySensor = await ActivitySensor.GetDefaultAsync();
                if (activitySensor != null)
                {
                    var calendar = new Calendar();
                    calendar.SetToNow();
                    calendar.AddDays(-1);
                    var yesterday = calendar.GetDateTime();

                    // Get history from yesterday onwards
                    var history = await ActivitySensor.GetSystemHistoryAsync(yesterday);

                    ScenarioOutput_Count.Text = history.Count.ToString();
                    if (history.Count > 0)
                    {
                        var reading1 = history[0];
                        ScenarioOutput_Activity1.Text = reading1.Activity.ToString();
                        ScenarioOutput_Confidence1.Text = reading1.Confidence.ToString();
                        ScenarioOutput_Timestamp1.Text = reading1.Timestamp.ToString("u");

                        var readingN = history[history.Count - 1];
                        ScenarioOutput_ActivityN.Text = readingN.Activity.ToString();
                        ScenarioOutput_ConfidenceN.Text = readingN.Confidence.ToString();
                        ScenarioOutput_TimestampN.Text = readingN.Timestamp.ToString("u");
                    }
                }
                else
                {
                    rootPage.NotifyUser("No activity sensors found", NotifyType.ErrorMessage);
                }
            }
            else
            {
                rootPage.NotifyUser("Access to activity sensors is denied", NotifyType.ErrorMessage);
            }
        }
        /// <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
            rootPage.NotifyUser(results.ToString(), NotifyType.StatusMessage);
        }
Example #19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DateTimePicker"/> class.
        /// </summary>
        protected DateTimePicker()
        {
            var languages = new List <string> {
                this.CalendarLanguage
            };
            var calendar = new Windows.Globalization.Calendar(languages, this.CalendarIdentifier, ClockIdentifiers.TwelveHour);

            this.calendarValidator      = new CalendarValidator(calendar);
            this.selectorUtcValue       = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc);
            this.utcValue               = this.selectorUtcValue;
            Window.Current.SizeChanged += this.Current_SizeChanged;
        }
Example #20
0
        private void ValidateFormat(
            string culture,
            string calendar,
            string clock,
            DateTimeOffset date,
            string yearAsPaddedString,
            string yearAsString,
            string monthAsPaddedNumericString,
            string monthAsSoloString,
            string monthAsString,
            string monthAsNumericString,
            string dayAsPaddedString,
            string dayAsString,
            string hourAsPaddedString,
            string hourAsString,
            string minuteAsPaddedString,
            string minuteAsString,
            string secondAsPaddedString,
            string secondAsString,
            string nanosecondAsPaddedString,
            string nanosecondAsString,
            string dayOfWeekAsSoloString,
            string dayOfWeekAsString
            )
        {
            var SUT = new WG.Calendar(new[] { culture }, calendar, clock);

            SUT.SetDateTime(date);

            using (new AssertionScope("Calendar Format"))
            {
                SUT.YearAsPaddedString(2).Should().Be(yearAsPaddedString, nameof(yearAsPaddedString));
                SUT.YearAsString().Should().Be(yearAsString, nameof(yearAsString));
                SUT.MonthAsPaddedNumericString(2).Should().Be(monthAsPaddedNumericString, nameof(monthAsPaddedNumericString));
                SUT.MonthAsSoloString().Should().Be(monthAsSoloString, nameof(monthAsSoloString));
                SUT.MonthAsString().Should().Be(monthAsString, nameof(monthAsString));
                SUT.MonthAsNumericString().Should().Be(monthAsNumericString, nameof(monthAsNumericString));
                SUT.DayAsPaddedString(2).Should().Be(dayAsPaddedString, nameof(dayAsPaddedString));
                SUT.DayAsString().Should().Be(dayAsString, nameof(dayAsString));
                SUT.HourAsPaddedString(2).Should().Be(hourAsPaddedString, nameof(hourAsPaddedString));
                SUT.HourAsString().Should().Be(hourAsString, nameof(hourAsString));
                SUT.MinuteAsPaddedString(2).Should().Be(minuteAsPaddedString, nameof(minuteAsPaddedString));
                SUT.MinuteAsString().Should().Be(minuteAsString, nameof(minuteAsString));
                SUT.SecondAsPaddedString(2).Should().Be(secondAsPaddedString, nameof(secondAsPaddedString));
                SUT.SecondAsString().Should().Be(secondAsString, nameof(secondAsString));
                SUT.NanosecondAsPaddedString(2).Should().Be(nanosecondAsPaddedString, nameof(nanosecondAsPaddedString));
                SUT.NanosecondAsString().Should().Be(nanosecondAsString, nameof(nanosecondAsString));
                SUT.DayOfWeekAsSoloString().Should().Be(dayOfWeekAsSoloString, nameof(dayOfWeekAsSoloString));
                SUT.DayOfWeekAsString().Should().Be(dayOfWeekAsString, nameof(dayOfWeekAsString));
            }
        }
 private string ReportCalendarData(Calendar calendar)
 {
     // Display individual date/time elements.
     return string.Format("In {0} time zone:   {1}   {2} {3}, {4}   {5}:{6}:{7} {8}  {9}",
                          calendar.GetTimeZone(),
                          calendar.DayOfWeekAsSoloString(),
                          calendar.MonthAsSoloString(),
                          calendar.DayAsPaddedString(2),
                          calendar.YearAsString(),
                          calendar.HourAsPaddedString(2),
                          calendar.MinuteAsPaddedString(2),
                          calendar.SecondAsPaddedString(2),
                          calendar.PeriodAsString(),
                          calendar.TimeZoneAsString(3));
 }
        /// <summary>
        /// This is a helper function to display calendar's properties in presentable format
        /// </summary>
        /// <param name="calendar"></param>
        private String GetCalendarProperties(Calendar calendar)
        {
            StringBuilder returnString = new StringBuilder();
            
            returnString.AppendLine("Calendar system: " + calendar.GetCalendarSystem());
            returnString.AppendLine("Numeral System: " + calendar.NumeralSystem);
            returnString.AppendLine("Resolved Language " + calendar.ResolvedLanguage);
            returnString.AppendLine("Name of Month: " + calendar.MonthAsSoloString());
            returnString.AppendLine("Day of Month: " + calendar.DayAsPaddedString(2));
            returnString.AppendLine("Day of Week: " + calendar.DayOfWeekAsSoloString());
            returnString.AppendLine("Year: " + calendar.YearAsString());
            returnString.AppendLine();

            return(returnString.ToString());
        }
        private void ShowResults()
        {
            // This scenario uses the Windows.Globalization.Calendar class to display the parts of a date.

            // Create Calendar objects using different constructors.
            Calendar calendar = new Calendar();
            Calendar japaneseCalendar = new Calendar(new[] { "ja-JP" }, CalendarIdentifiers.Japanese, ClockIdentifiers.TwelveHour);
            Calendar hebrewCalendar = new Calendar(new[] { "he-IL" }, CalendarIdentifiers.Hebrew, ClockIdentifiers.TwentyFourHour);

            // Display the results
            OutputTextBlock.Text =
                ReportCalendarData(calendar, "User's default calendar system") +
                ReportCalendarData(japaneseCalendar, "Calendar system") +
                ReportCalendarData(hebrewCalendar, "Calendar system");
        }
Example #24
0
 private static long GetTimeFromDateValue(DateTime untilDate)
 {
     if (untilDate == null)
     {
         return -1;
     }
     Calendar dateValue = new Calendar();
     dateValue.Year = untilDate.Year;//.set(Calendar.YEAR, untilDate.year());
     dateValue.Month = untilDate.Month - 1;//TODO 为什么要减1         .set(Calendar.MONTH, untilDate.month() - 1);
     dateValue.Day = untilDate.Day;//.set(Calendar.DAY_OF_MONTH, untilDate.day());
     dateValue.Hour = untilDate.Hour;//.set(Calendar.HOUR_OF_DAY, 0);
     dateValue.Minute = untilDate.Minute;//.set(Calendar.MINUTE, 0);
     dateValue.Second = untilDate.Second;//.set(Calendar.SECOND, 0);
     dateValue.Nanosecond = untilDate.Millisecond * 1000;//.set(Calendar.MILLISECOND, 0);
     return dateValue.GetDateTime().Ticks / TimeSpan.TicksPerMillisecond;//.getTimeInMillis();
 }
Example #25
0
    /**
 * This isn't a regular method, because there isn't exist utc date. It
 * convert date for example 2014/1/1 09:00 +0800 -> 2014/1/1 09:00 +0000
 *
 * @return utc date
 */
    private static DateTime ConvertDateToUTCDate(DateTime date, Calendar taskCal, Calendar utcCal)
    {
        taskCal.SetDateTime(date);
        utcCal.SetDateTime(taskCal.GetDateTime().DateTime.ToUniversalTime());
        return utcCal.GetDateTime().DateTime;
        //taskCal.setTime(date);
        //int year = taskCal.get(Calendar.YEAR);
        //int month = taskCal.get(Calendar.MONTH);
        //int day = taskCal.get(Calendar.DAY_OF_MONTH);
        //int hourOfDay = taskCal.get(Calendar.HOUR_OF_DAY);
        //int minute = taskCal.get(Calendar.MINUTE);
        //int second = taskCal.get(Calendar.SECOND);
        //utcCal.clear();
        //utcCal.set(year, month, day, hourOfDay, minute, second);
        //return utcCal.getTime();
    }
Example #26
0
        private void UpdateText(Windows.Globalization.Calendar calendar)
        {
            switch (this.owner.ComponentType)
            {
            case DateTimeComponentType.Day:
                this.headerText  = calendar.DayAsPaddedString(2);
                this.contentText = calendar.DayOfWeekAsSoloString();
                break;

            case DateTimeComponentType.Month:
                this.headerText  = calendar.MonthAsPaddedNumericString(2);
                this.contentText = calendar.MonthAsSoloString();
                break;

            case DateTimeComponentType.Year:
                this.headerText = calendar.YearAsPaddedString(4);
                if (calendar.GetCalendarSystem() == Windows.Globalization.CalendarIdentifiers.Gregorian &&
                    DateTime.IsLeapYear(calendar.GetUtcDateTime().Year))
                {
                    this.contentText = InputLocalizationManager.Instance.GetString("LeapYear");
                }
                else
                {
                    this.contentText = " ";
                }
                break;

            case DateTimeComponentType.Hour:
                this.headerText  = calendar.HourAsString();
                this.contentText = string.Empty;
                break;

            case DateTimeComponentType.Minute:
                this.headerText  = calendar.MinuteAsPaddedString(2);
                this.contentText = string.Empty;
                break;

            case DateTimeComponentType.AMPM:
                this.headerText  = calendar.PeriodAsString();
                this.contentText = string.Empty;
                break;
            }

            this.OnPropertyChanged(nameof(this.HeaderText));
            this.OnPropertyChanged(nameof(this.ContentText));
        }
        private void ShowResults()
        {
            // This scenario uses the Windows.Globalization.Calendar class to display the parts of a date.

            // Create Calendar objects using different Unicode extensions for different languages.
            // NOTE: Calendar (ca) and numeral system (nu) are the only supported extensions with any others being ignored.
            // Note that collation (co) extension is ignored in the last example.
            Calendar cal1 = new Calendar();
            Calendar cal2 = new Calendar(new[] { "ar-SA-u-ca-gregory-nu-Latn" });
            Calendar cal3 = new Calendar(new[] { "he-IL-u-nu-arab" });
            Calendar cal4 = new Calendar(new[] { "he-IL-u-ca-hebrew-co-phonebk" });

            // Display individual date/time elements.
            OutputTextBlock.Text =
                ReportCalendarData(cal1, "User's default Calendar object") +
                ReportCalendarData(cal2, "Calendar object with Arabic language, Gregorian Calendar and Latin Numeral System (ar-SA-ca-gregory-nu-Latn)") +
                ReportCalendarData(cal3, "Calendar object with Hebrew language, Default Calendar for that language and Arab Numeral System (he-IL-u-nu-arab)") +
                ReportCalendarData(cal4, "Calendar object with Hebrew language, Hebrew Calendar, Default Numeral System for that language and Phonebook collation (he-IL-u-ca-hebrew-co-phonebk)");
        }
        private void UpdateMinMaxYears()
        {
            if (_picker == null)
            {
                return;
            }

            // TODO: support non-gregorian calendars

            var winCalendar = new Windows.Globalization.Calendar(
                new string[0],
                Windows.Globalization.CalendarIdentifiers.Gregorian,
                Windows.Globalization.ClockIdentifiers.TwentyFourHour);

            var calendar = new NSCalendar(NSCalendarType.Gregorian);

            winCalendar.SetDateTime(MaxYear);
            winCalendar.Month = winCalendar.LastMonthInThisYear;
            winCalendar.Day   = winCalendar.LastDayInThisMonth;

            var maximumDateComponents = new NSDateComponents
            {
                Day   = winCalendar.Day,
                Month = winCalendar.Month,
                Year  = winCalendar.Year
            };

            _picker.MaximumDate = calendar.DateFromComponents(maximumDateComponents);

            winCalendar.SetDateTime(MinYear);
            winCalendar.Month = winCalendar.FirstMonthInThisYear;
            winCalendar.Day   = winCalendar.FirstDayInThisMonth;

            var minimumDateComponents = new NSDateComponents
            {
                Day   = winCalendar.Day,
                Month = winCalendar.Month,
                Year  = winCalendar.Year
            };

            _picker.MinimumDate = calendar.DateFromComponents(minimumDateComponents);
        }
Example #29
0
        /// <summary>
        /// Gets the UTC <see cref="DateTime"/> of the calendar.
        /// </summary>
        internal static DateTime GetUtcDateTime(this Windows.Globalization.Calendar calendar)
        {
            DateTime dateTime;

            if (calendar.Year == calendar.LastYearInThisEra)
            {
                calendar.AddYears(-1);
                dateTime = calendar.GetDateTime().UtcDateTime;
                if (dateTime > DateTime.MaxValue.AddYears(-1))
                {
                    dateTime = DateTime.MaxValue;
                }
                else
                {
                    dateTime = dateTime.AddYears(1);
                }

                calendar.AddYears(1);
            }
            else if (calendar.Year == calendar.FirstYearInThisEra)
            {
                calendar.AddYears(1);
                dateTime = calendar.GetDateTime().UtcDateTime;
                if (dateTime < DateTime.MinValue.AddYears(1))
                {
                    dateTime = DateTime.MinValue;
                }
                else
                {
                    dateTime = dateTime.AddYears(-1);
                }

                calendar.AddYears(-1);
            }
            else
            {
                dateTime = calendar.GetDateTime().UtcDateTime;
            }

            return(dateTime);
        }
Example #30
0
        /// <summary>
        /// Sets zero based calendar hour.
        /// </summary>
        internal static void SetZeroBasedHour(this Windows.Globalization.Calendar calendar, int hour)
        {
            if (calendar.GetClock() == ClockIdentifiers.TwentyFourHour)
            {
                if (hour < 0 || hour > 23)
                {
                    throw new ArgumentException("Hour should be between 0 and 23.");
                }

                calendar.AddHours(hour - calendar.Hour);
            }
            else
            {
                if (hour < 0 || hour > 11)
                {
                    throw new ArgumentException("Hour should be between 0 and 11.");
                }
                var calendarHour = calendar.Hour == 12 ? 0 : calendar.Hour;
                calendar.AddHours(hour - calendarHour);
            }
        }
        /// <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 uses the Windows.Globalization.Calendar class to display the calendar
            // system statistics.
            
            // Store results here.
            StringBuilder results = new StringBuilder();

            // Create Calendar objects using different constructors.
            Calendar calendar = new Calendar();
            Calendar japaneseCalendar = new Calendar(new[] { "ja-JP" }, CalendarIdentifiers.Japanese, ClockIdentifiers.TwelveHour);
            Calendar hebrewCalendar = new Calendar(new[] { "he-IL" }, CalendarIdentifiers.Hebrew, ClockIdentifiers.TwentyFourHour);

            // Display individual date/time elements.
            results.AppendLine("User's default calendar system: " + calendar.GetCalendarSystem());
            results.AppendLine("Months in this Year: " + calendar.NumberOfMonthsInThisYear);
            results.AppendLine("Days in this Month: " + calendar.NumberOfDaysInThisMonth);
            results.AppendLine("Hours in this Period: " + calendar.NumberOfHoursInThisPeriod);
            results.AppendLine("Era: " + calendar.EraAsString());
            results.AppendLine();
            results.AppendLine("Calendar system: " + japaneseCalendar.GetCalendarSystem());
            results.AppendLine("Months in this Year: " + japaneseCalendar.NumberOfMonthsInThisYear);
            results.AppendLine("Days in this Month: " + japaneseCalendar.NumberOfDaysInThisMonth);
            results.AppendLine("Hours in this Period: " + japaneseCalendar.NumberOfHoursInThisPeriod);
            results.AppendLine("Era: " + japaneseCalendar.EraAsString());
            results.AppendLine();
            results.AppendLine("Calendar system: " + hebrewCalendar.GetCalendarSystem());
            results.AppendLine("Months in this Year: " + hebrewCalendar.NumberOfMonthsInThisYear);
            results.AppendLine("Days in this Month: " + hebrewCalendar.NumberOfDaysInThisMonth);
            results.AppendLine("Hours in this Period: " + hebrewCalendar.NumberOfHoursInThisPeriod);
            results.AppendLine("Era: " + hebrewCalendar.EraAsString());
            results.AppendLine();

            // Display results
            rootPage.NotifyUser(results.ToString(), NotifyType.StatusMessage);
        }
Example #32
0
        //public void fillCalendar()
        //{
        //    Windows.Globalization.Calendar calendar = new Windows.Globalization.Calendar();
            
        //    List<NameValueItem> dList = new List<NameValueItem>();

        //    int noOfDaysInTheSelectedMonth = 0;
        //    int shift = 0;
        //    string firstDay=String.Empty;

        //    if(flip == 0)
        //    {
                
        //        SelectedMonth = calendar.MonthAsSoloString();
                
        //        SelectedYear = calendar.Year.ToString();
        //       // firstDay = new DateTime(Convert.ToInt32(SelectedYear), DateTime.ParseExact(SelectedMonth, "MMMM", CultureInfo.CurrentCulture).Month, 1).ToString("dddd");
        //    }
            
        //    if(flip == -1)
        //    {
        //         int temp = DateTime.ParseExact(SelectedMonth, "MMMM", CultureInfo.CurrentCulture).Month;
        //         if (temp == 1)
        //         {
        //             temp = 12;
        //         }
        //         else
        //         {
        //             temp--;
        //         }
        //        SelectedMonth = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(temp);
        //        if(temp!=12 )
        //        {
        //            //SelectedYear = calendar.Year.ToString();
        //        }
        //        else
        //        {
        //            int tempYear = Convert.ToInt32(SelectedYear);
        //            tempYear--;
        //            SelectedYear = tempYear.ToString();

        //        }

                
        //    }

        //    if(flip ==1)
        //    {
        //        {
        //            int temp = DateTime.ParseExact(SelectedMonth, "MMMM", CultureInfo.CurrentCulture).Month;
        //            if (temp == 12)
        //            { 
        //                temp = 1; 
        //            }
        //            else
        //            {
        //                temp++;
        //            }
        //            SelectedMonth = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(temp);
        //            if (temp != 1)
        //            {
        //            }
        //            else
        //            {
        //                int tempYear =Convert.ToInt32(SelectedYear);
        //                tempYear++;
        //                SelectedYear = tempYear.ToString();

        //            }


        //        }
        //    }


        //    noOfDaysInTheSelectedMonth = DateTime.DaysInMonth(Convert.ToInt32(SelectedYear), DateTime.ParseExact(SelectedMonth, "MMMM", CultureInfo.CurrentCulture).Month);
        //    firstDay = new DateTime(Convert.ToInt32(SelectedYear), DateTime.ParseExact(SelectedMonth, "MMMM", CultureInfo.CurrentCulture).Month, 1).ToString("dddd");

        //    switch (firstDay)
        //    {
        //        case "Sunday": shift = 0;
        //            break;
        //        case "Monday": shift = 1;
        //            break;
        //        case "Tuesday": shift = 2;
        //            break;
        //        case "Wednesday": shift = 3;
        //            break;
        //        case "Thursday": shift = 4;
        //            break;
        //        case "Friday": shift = 5;
        //            break;
        //        case "Saturday": shift = 6;
        //            break;
        //    }

        //    while (shift > 0)
        //    {
        //        dList.Add(new NameValueItem());
        //        shift--;
        //    }

        //    for (int i = 1; i <= noOfDaysInTheSelectedMonth; i++)
        //    {
        //        DateTime loopDate = new DateTime(Convert.ToInt32(SelectedYear), DateTime.ParseExact(SelectedMonth, "MMMM", CultureInfo.CurrentCulture).Month, i);
        //        if (loopDate.ToString("MMMM dd, yyyy").Equals(CurrentDate.ToString("MMMM dd, yyyy")))
        //        {
        //            dList.Add(new NameValueItem { Name = (new DateTime(Convert.ToInt32(SelectedYear), DateTime.ParseExact(SelectedMonth, "MMMM", CultureInfo.CurrentCulture).Month, i).ToString("dddd")), Value = i.ToString(), Info = String.Empty, Color = "Blue", date = DateTime.Now });

        //        }
        //        else
        //        {
        //            if (i == 6)
        //            {
        //                dList.Add(new NameValueItem { Name = (new DateTime(Convert.ToInt32(SelectedYear), DateTime.ParseExact(SelectedMonth, "MMMM", CultureInfo.CurrentCulture).Month, i).ToString("dddd")), Value = i.ToString(), Info = "Abdominal Pain", Color = "Pink", date = DateTime.Now });

        //            }
        //            else if(i==15)
        //            {
        //                dList.Add(new NameValueItem { Name = (new DateTime(Convert.ToInt32(SelectedYear), DateTime.ParseExact(SelectedMonth, "MMMM", CultureInfo.CurrentCulture).Month, i).ToString("dddd")), Value = i.ToString(), Info = "Leg Fracture", Color = "Pink", date = DateTime.Now });
        //            }
        //            else if (i == 19)
        //            {
        //                dList.Add(new NameValueItem { Name = (new DateTime(Convert.ToInt32(SelectedYear), DateTime.ParseExact(SelectedMonth, "MMMM", CultureInfo.CurrentCulture).Month, i).ToString("dddd")), Value = i.ToString(), Info = "Feaver", Color = "Pink", date = DateTime.Now });
        //            }
        //            else
        //            {
        //                dList.Add(new NameValueItem { Name = (new DateTime(Convert.ToInt32(SelectedYear), DateTime.ParseExact(SelectedMonth, "MMMM", CultureInfo.CurrentCulture).Month, i).ToString("dddd")), Value = i.ToString(), Info = String.Empty, Color = "AliceBlue", date = DateTime.Now });

        //            }
        //        }
        //    }

        //    MonthGridView.ItemsSource = dList;
        //}

        //private void previousMonthButton_Click(object sender, RoutedEventArgs e)
        //{
        //    flip = -1;
        //    fillCalendar();

        //}

        //private void nextMonthButton_Click(object sender, RoutedEventArgs e)
        //{
        //    flip = 1;
        //    fillCalendar();
        //}



        //private async void MonthGridView_ItemClick(object sender, ItemClickEventArgs e)
        //{

        //    if (((NameValueItem)e.ClickedItem).Value!= null)
        //    {

        //        Window currentWindow = Window.Current;

        //        Point point, myPoint;

        //        try
        //        {
        //            point = currentWindow.CoreWindow.PointerPosition;
        //        }
        //        catch (UnauthorizedAccessException)
        //        {
        //            myPoint = new Point(double.NegativeInfinity, double.NegativeInfinity);
        //        }

        //        Rect bounds = currentWindow.Bounds;

        //        myPoint = new Point(DipToPixel(point.X - bounds.X), DipToPixel(point.Y - bounds.Y));

        //        LightDismissAnimatedPopup.VerticalOffset = myPoint.Y - 200;

        //        LightDismissAnimatedPopup.HorizontalOffset = myPoint.X - 310;


        //        if (!LightDismissAnimatedPopup.IsOpen) { LightDismissAnimatedPopup.IsOpen = true; }
        //        LightDismissAnimatedPopupTextBlock.Text = ((NameValueItem)e.ClickedItem).Value;
        //        LightDismissAnimatedPopupTextBlock2.Text = ((NameValueItem)e.ClickedItem).date.ToString();
        //    }
        //}
        //private static double DipToPixel(double dip)
        //{
        //    return (dip * DisplayProperties.LogicalDpi) / 96.0;
        //}

     
        //// Handles the Click event on the Button within the simple Popup control and simply closes it.
        //private void CloseAnimatedPopupClicked(object sender, RoutedEventArgs e)
        //{
        //    if (LightDismissAnimatedPopup.IsOpen) { LightDismissAnimatedPopup.IsOpen = false; }
        //}

        //private void Button_Click(object sender, RoutedEventArgs e)
        //{
        //    CurrentViewMode = ViewMode.Weekly.ToString();
        //    ShowMonthlyCalendar = Visibility.Collapsed;
        //    ShowWeeklyCalendar = Visibility.Visible;
        //   // Output.Visibility = ShowMonthlyCalendar;
        //}


        public async void fillWeeklyCalendar()
        {

            LeftMonth = String.Empty;
            LeftYear = String.Empty;
            RightMonth = String.Empty;
            RightYear = String.Empty;

            Windows.Globalization.Calendar calendar = new Windows.Globalization.Calendar();


            List<NameValueItem3> dList = new List<NameValueItem3>();

            List<WeekDay> weekList = new List<WeekDay>(7);

            if (flip2 == 0)
            {
                if (String.IsNullOrEmpty(SelectedMonth))
                    SelectedMonth = calendar.MonthAsSoloString();
                if (String.IsNullOrEmpty(SelectedYear))
                    SelectedYear = calendar.Year.ToString();



                SelectedWeek = 1;

            }
            if (flip2 == -1)
            {


                if (SelectedWeek == 1)
                {
                    SelectedWeek = 4;

                    if ((DateTime.ParseExact(SelectedMonth, "MMMM", CultureInfo.CurrentCulture).Month) == 1)
                    {
                        SelectedMonth = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(12);
                        SelectedYear = ((Convert.ToInt32(SelectedYear)) - 1).ToString();
                    }
                    else
                    {
                        SelectedMonth = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.ParseExact(SelectedMonth, "MMMM", CultureInfo.CurrentCulture).Month - 1);
                    }

                }
                else
                {
                    SelectedWeek--;
                }




            }

            if (flip2 == 1)
            {



                if (SelectedWeek == 4)
                {
                    SelectedWeek = 1;

                    if ((DateTime.ParseExact(SelectedMonth, "MMMM", CultureInfo.CurrentCulture).Month) == 12)
                    {
                        SelectedMonth = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(1);
                        SelectedYear = ((Convert.ToInt32(SelectedYear)) + 1).ToString();
                    }
                    else
                    {
                        SelectedMonth = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.ParseExact(SelectedMonth, "MMMM", CultureInfo.CurrentCulture).Month + 1);
                    }

                }
                else
                {
                    SelectedWeek++;
                }
            }
            int noOfDaysInTheSelectedMonth = 0;
            int shift = 0;
            string firstDay = String.Empty;




            if (SelectedWeek == 1)
            {
                //int noOfDaysInTheSelectedMonth = 0;
                //int shift = 0;
                //string firstDay = String.Empty;

                noOfDaysInTheSelectedMonth = DateTime.DaysInMonth(Convert.ToInt32(SelectedYear), DateTime.ParseExact(SelectedMonth, "MMMM", CultureInfo.CurrentCulture).Month);
                firstDay = new DateTime(Convert.ToInt32(SelectedYear), DateTime.ParseExact(SelectedMonth, "MMMM", CultureInfo.CurrentCulture).Month, 1).ToString("dddd");

                switch (firstDay)
                {
                    case "Sunday": shift = 0;
                        break;
                    case "Monday": shift = 1;
                        break;
                    case "Tuesday": shift = 2;
                        break;
                    case "Wednesday": shift = 3;
                        break;
                    case "Thursday": shift = 4;
                        break;
                    case "Friday": shift = 5;
                        break;
                    case "Saturday": shift = 6;
                        break;
                }

                int NumberOfPreviousMonthDays;
                string previuosMonth;
                string previousMonthYear;

                if (shift != 0)
                {

                    if (DateTime.ParseExact(SelectedMonth, "MMMM", CultureInfo.CurrentCulture).Month != 1)
                    {
                        NumberOfPreviousMonthDays = DateTime.DaysInMonth(Convert.ToInt32(SelectedYear), DateTime.ParseExact(SelectedMonth, "MMMM", CultureInfo.CurrentCulture).Month - 1);
                        previuosMonth = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.ParseExact(SelectedMonth, "MMMM", CultureInfo.CurrentCulture).Month - 1);//
                        previousMonthYear = SelectedYear;
                    }
                    else
                    {
                        NumberOfPreviousMonthDays = DateTime.DaysInMonth(Convert.ToInt32(SelectedYear) - 1, 12);
                        previuosMonth = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(12);// CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.ParseExact(SelectedMonth, "MMMM", CultureInfo.CurrentCulture).Month - 1);//
                        previousMonthYear = (Convert.ToInt32(SelectedYear) - 1).ToString();

                    }

                    for (int i = shift - 1; i >= 0; i--)
                    {
                        weekList.Add(new WeekDay { Year = previousMonthYear, Month = previuosMonth, Day = NumberOfPreviousMonthDays - i });
                    }

                    for (int i = 1; i <= 7 - shift; i++)
                    {
                        weekList.Add(new WeekDay { Year = SelectedYear, Month = SelectedMonth, Day = i });
                        if (i == 7 - shift)
                        {
                            ReachedDayInWeeklyCalendar = weekList.Last();
                            StartDayInWeeklyCalendar = weekList.First();

                        }
                    }

                    LeftMonth = previuosMonth;
                    LeftYear = previousMonthYear;

                    RightMonth = SelectedMonth;
                    //  MonthNameTextBlock3.Text =SelectedMonth  ;
                    RightYear = selectedYear;
                }
                if (shift == 0)
                {
                    for (int i = 1; i <= 7; i++)
                    {

                        weekList.Add(new WeekDay { Year = SelectedYear, Month = SelectedMonth, Day = i });
                        if (i == 7)
                        {
                            ReachedDayInWeeklyCalendar = weekList.Last();
                            StartDayInWeeklyCalendar = weekList.First();
                        }
                    }

                    LeftMonth = SelectedMonth;
                    LeftYear = SelectedYear;

                    RightMonth = String.Empty;
                    RightYear = String.Empty;
                }

                //fill dList


                //  weekList.Clear();


            }
            else if (SelectedWeek == 2 || SelectedWeek == 3 || SelectedWeek == 4)
            {
                if (!backward)
                {
                    for (int i = ReachedDayInWeeklyCalendar.Day + 1; i <= (ReachedDayInWeeklyCalendar.Day + 7); i++)
                    {
                        weekList.Add(new WeekDay { Year = SelectedYear, Month = SelectedMonth, Day = i });
                        if (i == ReachedDayInWeeklyCalendar.Day + 7)
                        {
                            ReachedDayInWeeklyCalendar = weekList.Last();
                            StartDayInWeeklyCalendar = weekList.First();
                            break;
                        }
                    }



                }

                else //backward true
                {

                    if (StartDayInWeeklyCalendar.Day - 1 != 0)
                    {
                        for (int i = StartDayInWeeklyCalendar.Day - 7; i <= (StartDayInWeeklyCalendar.Day - 1); i++)
                        {

                            weekList.Add(new WeekDay { Year = SelectedYear, Month = SelectedMonth, Day = i });
                            if (i == StartDayInWeeklyCalendar.Day - 1)
                            {
                                ReachedDayInWeeklyCalendar = weekList.Last();
                                StartDayInWeeklyCalendar = weekList.First();
                                break;
                            }


                        }
                    }
                    else
                    {
                        if (DateTime.ParseExact(SelectedMonth, "MMMM", CultureInfo.CurrentCulture).Month != 1)
                        {
                            noOfDaysInTheSelectedMonth = DateTime.DaysInMonth(Convert.ToInt32(SelectedYear), DateTime.ParseExact(SelectedMonth, "MMMM", CultureInfo.CurrentCulture).Month);
                            //SelectedMonth = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.ParseExact(SelectedMonth, "MMMM", CultureInfo.CurrentCulture).Month - 1);//
                            //SelectedYear = SelectedYear;
                        }
                        else
                        {
                            noOfDaysInTheSelectedMonth = DateTime.DaysInMonth(Convert.ToInt32(SelectedYear) - 1, 12);
                            //SelectedMonth = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(12);// CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.ParseExact(SelectedMonth, "MMMM", CultureInfo.CurrentCulture).Month - 1);//
                            //SelectedYear = (Convert.ToInt32(SelectedYear) - 1).ToString();

                        }

                        for (int i = noOfDaysInTheSelectedMonth - 6; i <= (noOfDaysInTheSelectedMonth - 0); i++)
                        {

                            weekList.Add(new WeekDay { Year = SelectedYear, Month = SelectedMonth, Day = i });
                            if (i == (noOfDaysInTheSelectedMonth - 0))
                            {
                                ReachedDayInWeeklyCalendar = weekList.Last();
                                StartDayInWeeklyCalendar = weekList.First();
                                break;
                            }


                        }



                    }



                }


                LeftMonth = SelectedMonth;
                LeftYear = SelectedYear;
                RightMonth = String.Empty;
                RightYear = String.Empty;



            }

            List<User> empList = await  User.ReadUsersList();


            for (int i = 0; i < empList.Count*9; i++)
            {
                OutLookEvent myOEvent = null;
                if (i % 9 == 0)
                {
                    dList.Add(new NameValueItem3() { timeItem = true, time = new TimeSpan(i / 9, 0, 0), Width = 3, timeStr = "Employee Name", Color1 = "AliceBlue" }); //( new TimeSpan(i / 9, 0, 0)).ToString()
               
                //fill employee names
                }

                else if ((i % 9)-1 == 7)
                {
                    //calculate work hours
                    dList.Add(new NameValueItem3() { timeItem = true, time = new TimeSpan(i / 9, 0, 0), Width = 1, timeStr = "Total", Color1 = "AliceBlue" }); //( new TimeSpan(i / 9, 0, 0)).ToString()

                }

                else 
                {

                    DateTime loopDate = new DateTime(Convert.ToInt32(weekList.ElementAt((i % 9) - 1).Year),
                           DateTime.ParseExact(weekList.ElementAt((i % 9) - 1).Month, "MMMM", CultureInfo.CurrentCulture).Month,
                           weekList.ElementAt((i % 9) - 1).Day);

                  
                    dList.Add(new NameValueItem3() { timeItem = false, time = new TimeSpan(i / 9, 0, 0), Width = 3, weekDay = weekList.ElementAt((i % 9) - 1), Color1 = (myOEvent != null ? "Wheat" : "AliceBlue"), myOutLookEvent = myOEvent });
                  
                    
                    if (i > 0 || i < 8)
                    {
                        //  if(myOEvent.isAllDay)
                        switch (i)
                        {
                            case 1: Sunday.Text = (new DateTime(Convert.ToInt32(weekList.ElementAt((i % 9) - 1).Year),
                                DateTime.ParseExact(weekList.ElementAt((i % 9) - 1).Month, "MMMM", CultureInfo.CurrentCulture).Month,
                                weekList.ElementAt((i % 9) - 1).Day)
                                ).DayOfWeek.ToString() + " " + weekList.ElementAt((i % 9) - 1).Day;
                              
                                break;
                            case 2: Monday.Text = (new DateTime(Convert.ToInt32(weekList.ElementAt((i % 9) - 1).Year),
                                 DateTime.ParseExact(weekList.ElementAt((i % 9) - 1).Month, "MMMM", CultureInfo.CurrentCulture).Month,
                                 weekList.ElementAt((i % 9) - 1).Day)
                                 ).DayOfWeek.ToString() + " " + weekList.ElementAt((i % 9) - 1).Day;
                              
                                break;
                            case 3: Tuesday.Text = (new DateTime(Convert.ToInt32(weekList.ElementAt((i % 9) - 1).Year),
                                DateTime.ParseExact(weekList.ElementAt((i % 9) - 1).Month, "MMMM", CultureInfo.CurrentCulture).Month,
                                weekList.ElementAt((i % 9) - 1).Day)
                                ).DayOfWeek.ToString() + " " + weekList.ElementAt((i % 9) - 1).Day;
                               
                                break;
                            case 4: Wednesday.Text = (new DateTime(Convert.ToInt32(weekList.ElementAt((i % 9) - 1).Year),
                                DateTime.ParseExact(weekList.ElementAt((i % 9) - 1).Month, "MMMM", CultureInfo.CurrentCulture).Month,
                                weekList.ElementAt((i % 9) - 1).Day)
                                ).DayOfWeek.ToString() + " " + weekList.ElementAt((i % 9) - 1).Day;
                               
                                break;
                            case 5: Thursday.Text = (new DateTime(Convert.ToInt32(weekList.ElementAt((i % 9) - 1).Year),
                                DateTime.ParseExact(weekList.ElementAt((i % 9) - 1).Month, "MMMM", CultureInfo.CurrentCulture).Month,
                                weekList.ElementAt((i % 9) - 1).Day)
                                ).DayOfWeek.ToString() + " " + weekList.ElementAt((i % 9) - 1).Day;
                              
                                break;
                            case 6: Friday.Text = (new DateTime(Convert.ToInt32(weekList.ElementAt((i % 9) - 1).Year),
                                DateTime.ParseExact(weekList.ElementAt((i % 9) - 1).Month, "MMMM", CultureInfo.CurrentCulture).Month,
                                weekList.ElementAt((i % 9) - 1).Day)
                                ).DayOfWeek.ToString() + " " + weekList.ElementAt((i % 9) - 1).Day;
                              
                                break;
                            case 7:


                                Saturday.Text = (new DateTime(Convert.ToInt32(weekList.ElementAt((i % 9) - 1).Year),
                                DateTime.ParseExact(weekList.ElementAt((i % 9) - 1).Month, "MMMM", CultureInfo.CurrentCulture).Month,
                                weekList.ElementAt((i % 9) - 1).Day)
                                ).DayOfWeek.ToString() + " " + weekList.ElementAt((i % 9) - 1).Day;
                             
                                break;


                        }
                       
                    }
                }

              
            }

            flip2 = 0;
            backward = false;
            WeekGridView.ItemsSource = dList;
            weekList.Clear();
            Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
            {
                WeekGridView.ScrollIntoView(dList.ElementAt(147));
            });

        }
Example #33
0
 private static DateTime ConvertUtcDateToDate(DateTime utcDate, Calendar taskCal, Calendar utcCal)
 {
     utcCal.SetDateTime(utcDate);
     taskCal.SetDateTime(utcCal.GetDateTime().DateTime);
     return taskCal.GetDateTime().DateTime;
     //int year = utcCal.Year;//.get(Calendar.YEAR);
     //int month = utcCal.Month;//.get(Calendar.MONTH);
     //int day = utcCal.Day;//.get(Calendar.DAY_OF_MONTH);
     //int hourOfDay = utcCal.Hour;//.get(Calendar.HOUR_OF_DAY);
     //int minute = utcCal.Minute;//.get(Calendar.MINUTE);
     //int second = utcCal.Second;//.get(Calendar.SECOND);
     ////taskCal.clear();
     //taskCal.set(year, month, day, hourOfDay, minute, second);
     //return taskCal.getTime();
 }
Example #34
0
 internal override string GetValueStringForNonGregorianCalendars(Windows.Globalization.Calendar calendar)
 {
     return(string.Format("{0}/{1}/{2}", calendar.MonthAsNumericString(), calendar.DayAsString(), calendar.YearAsString()));
 }
        /// <summary>
        /// This is the click handler for the 'Default' button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Display_Click(object sender, RoutedEventArgs e)
        {
            // This scenario uses the Windows.Globalization.Calendar class to enumerate through a calendar and
            // perform calendar math
            StringBuilder results = new StringBuilder();

            results.AppendLine("The number of years in each era of the Japanese era calendar is not regular. It is determined by the length of the given imperial era:\n");

            // Create Japanese calendar.
            Calendar calendar = new Calendar(new[] { "en-US" }, CalendarIdentifiers.Japanese, ClockIdentifiers.TwentyFourHour);

            // Enumerate all supported years in all supported Japanese eras.
            for (calendar.Era = calendar.FirstEra; true; calendar.AddYears(1))
            {
                // Process current era.
                results.AppendLine("Era " + calendar.EraAsString() + " contains " + calendar.NumberOfYearsInThisEra + " year(s)");

                // Enumerate all years in this era.
                for (calendar.Year = calendar.FirstYearInThisEra; true; calendar.AddYears(1))
                {
                    // Begin sample processing of current year.

                    // Move to first day of year. Change of month can affect day so order of assignments is important.
                    calendar.Month = calendar.FirstMonthInThisYear;
                    calendar.Day = calendar.FirstDayInThisMonth;

                    // Set time to midnight (local).
                    calendar.Period = calendar.FirstPeriodInThisDay;    // All days have 1 or 2 periods depending on clock type
                    calendar.Hour = calendar.FirstHourInThisPeriod;     // Hours start from 12 or 0 depending on clock type
                    calendar.Minute = 0;
                    calendar.Second = 0;
                    calendar.Nanosecond = 0;

                    if (calendar.Year % 1000 == 0)
                    {
                        results.AppendLine();
                    }
                    else if (calendar.Year % 10 == 0)
                    {
                        results.Append(".");
                    }

                    // End sample processing of current year.

                    // Break after processing last year.
                    if (calendar.Year == calendar.LastYearInThisEra)
                    {
                        break;
                    }
                }
                results.AppendLine();

                // Break after processing last era.
                if (calendar.Era == calendar.LastEra)
                {
                    break;
                }
            }

            // This section shows enumeration through the hours in a day to demonstrate that the number of time units in a given period (hours in a day, minutes in an hour, etc.)
            // should not be regarded as fixed. With Daylight Saving Time and other local calendar adjustments, a given day may have not have 24 hours, and
            // a given hour may not have 60 minutes, etc.
            results.AppendLine("\nThe number of hours in a day is not invariable. The US calendar transitions from DST to standard time on 4 November 2012:\n");

            // Create a DateTimeFormatter to display dates
            DateTimeFormatter displayDate = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longdate");

            // Create a gregorian calendar for the US with 12-hour clock format
            Calendar currentCal = new Windows.Globalization.Calendar(new string[] { "en-US" }, CalendarIdentifiers.Gregorian, ClockIdentifiers.TwentyFourHour, "america/los_angeles");

            // Set the calendar to a the date of the Daylight Saving Time-to-Standard Time transition for the US in 2012.
            // DST ends in the US at 02:00 on 4 November 2012
            DateTime dstDate = new DateTime(2012, 11, 4);  
            currentCal.SetDateTime(dstDate);

            // Set the current calendar to one day before DST change. Create a second calendar for comparision and set it to one day after DST change.
            Calendar endDate = currentCal.Clone();
            currentCal.AddDays(-1);
            endDate.AddDays(1);

            // Enumerate the day before, the day of, and the day after the 2012 DST-to-Standard time transition
            while (currentCal.Day <= endDate.Day)
            {
                // Process current day.
                DateTimeOffset date = currentCal.GetDateTime();
                results.AppendFormat("{0} contains {1} hour(s)\n", displayDate.Format(date), currentCal.NumberOfHoursInThisPeriod);

                // Enumerate all hours in this day.
                // Create a calendar to represent the following day.
                Calendar nextDay = currentCal.Clone();
                nextDay.AddDays(1);
                for (currentCal.Hour = currentCal.FirstHourInThisPeriod; true; currentCal.AddHours(1)) 
                {
                    // Display the hour for each hour in the day.             
                    results.AppendFormat("{0} ", currentCal.HourAsPaddedString(2));

                    // Break upon reaching the next period (i.e. the first period in the following day).
                    if (currentCal.Day == nextDay.Day && currentCal.Period == nextDay.Period) 
                    {
                        break;
                    }
                }

                results.AppendLine();
            }

            // Display results
            OutputTextBlock.Text = results.ToString();
        }
Example #36
0
        public static List<DateTime> GetNextDueDate(String repeatFlag, DateTime dueDate, String repeatFrom, DateTime completedTime, String timeZone, int limit)
        {
            List<DateTime> dueDates = new List<DateTime>();
            if (string.IsNullOrEmpty(repeatFlag) || dueDate == null)
            {
                return dueDates;
            }
            bool isLunar;
            try
            {
                TickRRule rRule = new TickRRule(repeatFlag);
                isLunar = rRule.IsLunarFrequency();
                if (IsRepeatFromCompleteTime(repeatFrom, completedTime))
                {
                    // update rRule, We must clear byDay and byMonthDay when the
                    // task repeat from completedTime.
                    rRule.SetByDay(new List<IWeekDay>());
                    rRule.SetByMonthDay(new int[0]);
                    repeatFlag = rRule.ToTickTickIcal();
                }
                if (rRule.GetCompletedRepeatCount() >= rRule.GetCount())
                {
                    return dueDates;
                }

                if (string.IsNullOrEmpty(timeZone))
                {
                    timeZone = NodaTime.DateTimeZoneProviders.Tzdb.GetSystemDefault().Id;
                }
                DateTimeZone taskTimeZone = DateTimeZoneProviders.Tzdb.GetZoneOrNull(timeZone); //.getTimeZone(timeZone);

                // TODO 有问题 阳历
                //GregorianCalendar taskCal = new GregorianCalendar(taskTimeZone);
                //GregorianCalendar utcCal = new GregorianCalendar(TimeUtils.utcTimezone());
                Calendar taskCal = new Calendar();
                taskCal.ChangeTimeZone(taskTimeZone.Id);
                Calendar utcCal = new Calendar();
                utcCal.ChangeTimeZone(DateTimeZoneProviders.Tzdb.GetSystemDefault().Id);

                DateTime taskStart = InitRepeatStartDate(repeatFrom, completedTime, dueDate, taskCal);
                DateTime utcStart = ConvertDateToUTCDate(taskStart, taskCal, utcCal);
                long untilDateTime = GetTimeFromDateValue(rRule.GetUntil());
                if (isLunar)
                {
                    //DateTime now = DateTime.UtcNow; // TODO 为什么要这么写?   DateTimeUtils.GetCurrentDate();
                    ////当前时间已经超过截止重复时间,必定没有下个有效的重复时间
                    //if (isAfterUntilDate(now, untilDateTime))
                    //{
                    //    return dueDates;
                    //}
                    //GregorianCalendar start = new GregorianCalendar();
                    //start.setTime(dueDate);
                    //Date next = getNextLunarDueDate(start, rRule);
                    //int i = 0;
                    //while (next != null && dueDates.size() < limit && !isAfterUntilDate(next,
                    //        untilDateTime))
                    //{
                    //    start.setTime(next);
                    //    next = getNextLunarDueDate(start, rRule);
                    //    if (next != null && !now.after(next))
                    //    {
                    //        dueDates.add(next);
                    //    }
                    //    if (i++ > 1000)
                    //    {
                    //        break;
                    //    }
                    //}
                    //if (dueDates.isEmpty())
                    //{
                    //    Log.e(TAG, "Get next due_date error: repeatFlag = " + repeatFlag);
                    //}
                    //return dueDates;
                }
                String rRuleString = rRule.ToIcal();
                if (untilDateTime > 0)
                {
                    rRuleString = RemoveKeyValueFromRRule(TickRRule.UNTIL_KEY, rRuleString);
                }
                // TODO 这是干嘛的。。。
                //DateIterator di = DateIteratorFactory.createDateIterator(rRuleString, utcStart, TimeUtils.utcTimezone(), true);
                if (Constants.RepeatFromStatus.DEFAULT.Equals(repeatFrom)
                        || string.IsNullOrEmpty(repeatFrom))
                {
                    // Repeat from default, next dueDate 不会返回小于Now
                    DateTime utcNow = ConvertDateToUTCDate(DateTime.UtcNow, taskCal, utcCal);//(DateTimeUtils.getCurrentDate(), taskCal, utcCal);
                    // TODO advanceTo 是什么,比什么早?
                    //if (utcNow > utcStart)
                    //{
                    //    di.advanceTo(utcNow);
                    //}
                }
                DateTime next;
                int count = 0;
                //while (di.hasNext() && dueDates.Count < limit)
                //{
                //    next = ConvertUtcDateToDate(di.next(), taskCal, utcCal);
                //    if (next > taskStart)
                //    {
                //        //得到的下次重复时间已超过截止重复时间,无效
                //        if (IsAfterUntilDate(next, untilDateTime))
                //        {
                //            return dueDates;
                //        }
                //        else
                //        {
                //            dueDates.Add(next);
                //        }
                //    }
                //    if (count++ > 10000)
                //    {
                //        // 对极端的情况跳出来,不要循环了。
                //        break;
                //    }
                //}
            }
            catch (Exception e)
            {
                //Log.e(TAG, "Get next due_date error: repeatFlag = " + repeatFlag, e);
            }
            return dueDates;

        }
        public static DateTime DurationAddToDate(String lexicalRepresentation, DateTime date)
        {
            if (date == null)
            {
                //throw new NullPointerException();
                throw new NullReferenceException();
            }

            Calendar calendar = new Calendar();
            // TODO 此处有问题
            calendar.SetDateTime(date);
            //calendar.Second =date.mi
            if (lexicalRepresentation == null)
            {
                throw new NullReferenceException();
            }
            String s = lexicalRepresentation;
            bool positive;
            int[] idx = new int[1];
            int length = s.Length;
            bool timeRequired = false;

            idx[0] = 0;
            if (length != idx[0] && s[(idx[0])] == '-')
            {
                idx[0]++;
                positive = false;
            }
            else
            {
                positive = true;
            }

            if (length != idx[0] && s[(idx[0]++)] != 'P')
            {
                //throw new ArgumentException(s); // ,idx[0]-1);
            }

            // phase 1: chop the string into chunks
            // (where a chunk is '<number><a symbol>'
            // --------------------------------------
            int dateLen = 0;
            String[] dateParts = new String[3];
            int[] datePartsIndex = new int[3];
            while (length != idx[0] && char.IsDigit(s[idx[0]]) && dateLen < 3)
            {
                datePartsIndex[dateLen] = idx[0];
                dateParts[dateLen++] = ParsePiece(s, idx);
            }

            if (length != idx[0])
            {
                if (s[idx[0]++] == 'T')
                {
                    timeRequired = true;
                }
                else
                {
                    //throw new IllegalArgumentException(s); // ,idx[0]-1);
                }
            }

            int timeLen = 0;
            String[] timeParts = new String[3];
            int[] timePartsIndex = new int[3];
            while (length != idx[0] && IsDigitOrPeriod(s[idx[0]]) && timeLen < 3)
            {
                timePartsIndex[timeLen] = idx[0];
                timeParts[timeLen++] = ParsePiece(s, idx);
            }

            if (timeRequired && timeLen == 0)
            {
                //throw new IllegalArgumentException(s); // ,idx[0]);
            }

            if (length != idx[0])
            {
                //throw new IllegalArgumentException(s); // ,idx[0]);
            }
            if (dateLen == 0 && timeLen == 0)
            {
                //throw new IllegalArgumentException(s); // ,idx[0]);
            }

            OrganizeParts(s, dateParts, datePartsIndex, dateLen, "YMD");
            OrganizeParts(s, timeParts, timePartsIndex, timeLen, "HMS");

            int year = ParseInteger(dateParts[0]);
            int months = ParseInteger(dateParts[1]);
            int days = ParseInteger(dateParts[2]);
            int hours = ParseInteger(timeParts[0]);
            int minutes = ParseInteger(timeParts[1]);
            int seconds = ParseInteger(timeParts[2]);

            if (positive)
            {
                calendar.Year += year;
                calendar.Month += months;
                calendar.Day += days;
                calendar.Hour += hours;
                calendar.Minute += minutes;
                calendar.Second += seconds;
                //calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) + year);
                //calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + months);
                //calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + days);
                //calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) + hours);
                //calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE) + minutes);
                //calendar.set(Calendar.SECOND, calendar.get(Calendar.SECOND) + seconds);
            }
            else
            {
                calendar.Year -= year;
                calendar.Month -= months;
                calendar.Day -= days;
                calendar.Hour -= hours;
                calendar.Minute -= minutes;
                calendar.Second -= seconds;
                //calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) - year);
                //calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - months);
                //calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) - days);
                //calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - hours);
                //calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE) - minutes);
                //calendar.set(Calendar.SECOND, calendar.get(Calendar.SECOND) - seconds);
            }

            return calendar.GetDateTime().DateTime;
        }
Example #38
0
 public static DateTime? SetHMToDate(String timeHM, DateTime date)
 {
     if (date == null)
     {
         return null;
     }
     DateTime? timeDate = DateTimeUtils.ParseUTCTime(timeHM);
     if (timeDate == null)
     {
         return null;
     }
     Calendar calendar = new Calendar();
     calendar.SetDateTime(date);
     //int year = calendar.Year;//.get(Calendar.YEAR);
     //int month = calendar.Month;//.get(Calendar.MONTH);
     //int day = calendar.Day;//.get(Calendar.DAY_OF_MONTH);
     //calendar.SetDateTime(timeDate.Value);//.setTime(timeDate);
     //int hourOfDay = calendar.Hour;//.get(Calendar.HOUR_OF_DAY);
     //int minute = calendar.Minute;//.get(Calendar.MINUTE);
     ////calendar.clear();
     //calendar.set(year, month, day, hourOfDay, minute);
     return calendar.GetDateTime().DateTime;//.getTime();
 }
        /// <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;
        }
Example #40
0
        private int NumberOfRowsForMonth(Calendar calendar, DateTime fdayInThisMonth)
        {
            if(calendar.NumberOfDaysInThisMonth == 31)
            {
                if (fdayInThisMonth.DayOfWeek == DayOfWeek.Saturday ||
                   fdayInThisMonth.DayOfWeek == DayOfWeek.Sunday)
                {
                    return 6;
                }

                return 5;
            }

            if (calendar.NumberOfDaysInThisMonth == 30)
            {
                if (fdayInThisMonth.DayOfWeek == DayOfWeek.Sunday)
                {
                    return 6;
                }

                return 5;
            }

            return 5;
        }
Example #41
0
        private void Validate(
            string culture,
            string calendar,
            string clock,
            DateTimeOffset date,
            int year,
            int month,
            int day,
            int hours,
            int minutes,
            int seconds,
            int milliseconds,
            int offsetInSeconds,
            DayOfWeek dayOfWeek,
            int era,
            int firstDayInThisMonth,
            int firstEra,
            int firstHourInThisPeriod,
            int firstMinuteInThisHour,
            int firstMonthInThisYear,
            int firstPeriodInThisDay,
            int firstSecondInThisMinute,
            int firstYearInThisEra,
            bool isDaylightSavingTime,
            int lastDayInThisMonth,
            int lastEra,
            int lastHourInThisPeriod,
            int lastMinuteInThisHour,
            int lastMonthInThisYear,
            int lastPeriodInThisDay,
            int lastSecondInThisMinute,
            int lastYearInThisEra,
            int numberOfEras,
            int numberOfHoursInThisPeriod,
            int numberOfMinutesInThisHour,
            int numberOfDaysInThisMonth,
            int numberOfMonthsInThisYear,
            int numberOfPeriodsInThisDay,
            int numberOfSecondsInThisMinute,
            int numberOfYearsInThisEra,
            string numeralSystem,
            int period,
            Action <WG.Calendar>?mutator = null
            )
        {
            var SUT = new WG.Calendar(new[] { culture }, calendar, clock);

            SUT.SetDateTime(date);

            mutator?.Invoke(SUT);

            using (new AssertionScope("Calendar Properties"))
            {
                SUT.Day.Should().Be(day, nameof(day));
                SUT.Month.Should().Be(month, nameof(month));
                SUT.Year.Should().Be(year, nameof(year));
                SUT.Hour.Should().Be(hours, nameof(hours));
                SUT.Minute.Should().Be(minutes, nameof(minutes));
                SUT.Second.Should().Be(seconds, nameof(seconds));
                SUT.Nanosecond.Should().Be(milliseconds * 1000, nameof(milliseconds));
                SUT.DayOfWeek.Should().Be(dayOfWeek, nameof(dayOfWeek));
                SUT.Era.Should().Be(era, nameof(era));
                SUT.FirstDayInThisMonth.Should().Be(firstDayInThisMonth, nameof(firstDayInThisMonth));
                SUT.FirstEra.Should().Be(firstEra, nameof(firstEra));
                SUT.FirstHourInThisPeriod.Should().Be(firstHourInThisPeriod, nameof(firstHourInThisPeriod));
                SUT.FirstMinuteInThisHour.Should().Be(firstMinuteInThisHour, nameof(firstMinuteInThisHour));
                SUT.FirstMonthInThisYear.Should().Be(firstMonthInThisYear, nameof(firstMonthInThisYear));
                SUT.FirstPeriodInThisDay.Should().Be(firstPeriodInThisDay, nameof(firstPeriodInThisDay));
                SUT.FirstSecondInThisMinute.Should().Be(firstSecondInThisMinute, nameof(firstSecondInThisMinute));
                SUT.FirstYearInThisEra.Should().Be(firstYearInThisEra, nameof(firstYearInThisEra));
                SUT.Languages.Should().HaveCount(1, "languages count");
                SUT.Languages.Should().HaveElementAt(0, culture, nameof(culture));
                SUT.LastDayInThisMonth.Should().Be(lastDayInThisMonth, nameof(lastDayInThisMonth));
                SUT.LastEra.Should().Be(lastEra, nameof(lastEra));
                SUT.LastHourInThisPeriod.Should().Be(lastHourInThisPeriod, nameof(lastHourInThisPeriod));
                SUT.LastMinuteInThisHour.Should().Be(lastMinuteInThisHour, nameof(lastMinuteInThisHour));
                SUT.LastMonthInThisYear.Should().Be(lastMonthInThisYear, nameof(lastMonthInThisYear));
                SUT.LastPeriodInThisDay.Should().Be(lastPeriodInThisDay, nameof(lastPeriodInThisDay));
                SUT.LastSecondInThisMinute.Should().Be(lastSecondInThisMinute, nameof(lastSecondInThisMinute));
                SUT.LastYearInThisEra.Should().Be(lastYearInThisEra, nameof(lastYearInThisEra));
                SUT.NumberOfDaysInThisMonth.Should().Be(numberOfDaysInThisMonth, nameof(numberOfDaysInThisMonth));
                SUT.NumberOfEras.Should().Be(numberOfEras, nameof(numberOfEras));
                SUT.NumberOfHoursInThisPeriod.Should().Be(numberOfHoursInThisPeriod, nameof(numberOfHoursInThisPeriod));
                SUT.NumberOfMinutesInThisHour.Should().Be(numberOfMinutesInThisHour, nameof(numberOfMinutesInThisHour));
                SUT.NumberOfMonthsInThisYear.Should().Be(numberOfMonthsInThisYear, nameof(numberOfMonthsInThisYear));
                SUT.NumberOfPeriodsInThisDay.Should().Be(numberOfPeriodsInThisDay, nameof(numberOfPeriodsInThisDay));
                SUT.NumberOfSecondsInThisMinute.Should().Be(numberOfSecondsInThisMinute, nameof(numberOfSecondsInThisMinute));
                SUT.NumberOfYearsInThisEra.Should().Be(numberOfYearsInThisEra, nameof(numberOfYearsInThisEra));
                SUT.Period.Should().Be(period, nameof(period));
                SUT.ResolvedLanguage.Should().Be(culture, nameof(culture));

                // Validation is disabled as timezone support is only using the current machine's timezone
                // SUT.IsDaylightSavingTime.Should().Be(isDaylightSavingTime, "isDaylightSavingTime");

                // Not yet supported.
                // SUT.NumeralSystem.Should().Be(numeralSystem, "numeralSystem");
            }
        }
        private void ShowResults_Click(object sender, RoutedEventArgs e)
        {
            // This scenario uses the Windows.Globalization.Calendar class to enumerate through a calendar and
            // perform calendar math
            StringBuilder results = new StringBuilder();

            results.AppendLine("The number of years in each era of the Japanese era calendar is not regular. " +
                               "It is determined by the length of the given imperial era:");
            results.AppendLine();

            // Create Japanese calendar.
            Calendar calendar = new Calendar(new[] { "en-US" }, CalendarIdentifiers.Japanese, ClockIdentifiers.TwentyFourHour);

            // Enumerate all supported years in all supported Japanese eras.
            for (calendar.Era = calendar.FirstEra; true; calendar.AddYears(1))
            {
                // Process current era.
                results.AppendLine("Era " + calendar.EraAsString() + " contains " + calendar.NumberOfYearsInThisEra + " year(s)");

                // Enumerate all years in this era.
                for (calendar.Year = calendar.FirstYearInThisEra; true; calendar.AddYears(1))
                {
                    // Begin sample processing of current year.

                    // Move to first day of year. Change of month can affect day so order of assignments is important.
                    calendar.Month = calendar.FirstMonthInThisYear;
                    calendar.Day   = calendar.FirstDayInThisMonth;

                    // Set time to midnight (local).
                    calendar.Period     = calendar.FirstPeriodInThisDay;  // All days have 1 or 2 periods depending on clock type
                    calendar.Hour       = calendar.FirstHourInThisPeriod; // Hours start from 12 or 0 depending on clock type
                    calendar.Minute     = 0;
                    calendar.Second     = 0;
                    calendar.Nanosecond = 0;

                    if (calendar.Year % 1000 == 0)
                    {
                        results.AppendLine();
                    }
                    else if (calendar.Year % 10 == 0)
                    {
                        results.Append(".");
                    }

                    // End sample processing of current year.

                    // Break after processing last year.
                    if (calendar.Year == calendar.LastYearInThisEra)
                    {
                        break;
                    }
                }
                results.AppendLine();

                // Break after processing last era.
                if (calendar.Era == calendar.LastEra)
                {
                    break;
                }
            }
            results.AppendLine();

            // This section shows enumeration through the hours in a day to demonstrate that the number of time units in a given period (hours in a day, minutes in an hour, etc.)
            // should not be regarded as fixed. With Daylight Saving Time and other local calendar adjustments, a given day may have not have 24 hours, and
            // a given hour may not have 60 minutes, etc.
            results.AppendLine("The number of hours in a day is not constant. " +
                               "The US calendar transitions from daylight saving time to standard time on 4 November 2012:\n");

            // Create a DateTimeFormatter to display dates
            DateTimeFormatter displayDate = new DateTimeFormatter("longdate");

            // Create a gregorian calendar for the US with 12-hour clock format
            Calendar currentCal = new Windows.Globalization.Calendar(new string[] { "en-US" }, CalendarIdentifiers.Gregorian, ClockIdentifiers.TwentyFourHour, "America/Los_Angeles");

            // Set the calendar to a the date of the Daylight Saving Time-to-Standard Time transition for the US in 2012.
            // DST ends in the America/Los_Angeles time zone at 4 November 2012 02:00 PDT = 4 November 2012 09:00 UTC.
            DateTime dstDate = new DateTime(2012, 11, 4, 9, 0, 0, DateTimeKind.Utc);

            currentCal.SetDateTime(dstDate);

            // Set the current calendar to one day before DST change. Create a second calendar for comparision and set it to one day after DST change.
            Calendar endDate = currentCal.Clone();

            currentCal.AddDays(-1);
            endDate.AddDays(1);

            // Enumerate the day before, the day of, and the day after the 2012 DST-to-Standard time transition
            while (currentCal.Day <= endDate.Day)
            {
                // Process current day.
                DateTimeOffset date = currentCal.GetDateTime();
                results.AppendFormat("{0} contains {1} hour(s)\n", displayDate.Format(date), currentCal.NumberOfHoursInThisPeriod);

                // Enumerate all hours in this day.
                // Create a calendar to represent the following day.
                Calendar nextDay = currentCal.Clone();
                nextDay.AddDays(1);
                for (currentCal.Hour = currentCal.FirstHourInThisPeriod; true; currentCal.AddHours(1))
                {
                    // Display the hour for each hour in the day.
                    results.AppendFormat("{0} ", currentCal.HourAsPaddedString(2));

                    // Break upon reaching the next period (i.e. the first period in the following day).
                    if (currentCal.Day == nextDay.Day && currentCal.Period == nextDay.Period)
                    {
                        break;
                    }
                }
                results.AppendLine();
            }

            // Display results
            OutputTextBlock.Text = results.ToString();
        }
Example #43
0
        public static DateTime? ClearSecondOfDay(DateTime date)
        {
            if (date == null)
            {
                return null;
            }
            Calendar c = new Calendar();
            c.SetDateTime(date);
            c.Second = 0;
            return c.GetDateTime().DateTime;

            //c.setTime(date);
            //c.set(Calendar.SECOND, 0);
            //c.set(Calendar.MILLISECOND, 0);
            //return c.getTime();
        }