public static void AddDays_Invalid(Calendar calendar) { AssertExtensions.Throws <ArgumentException>(null, () => calendar.AddDays(calendar.MaxSupportedDateTime, 1)); AssertExtensions.Throws <ArgumentException>(null, () => calendar.AddDays(calendar.MinSupportedDateTime, -1)); AssertExtensions.Throws <ArgumentException>(null, () => calendar.AddDays(DateTime.Now, -120001 * 30)); AssertExtensions.Throws <ArgumentException>(null, () => calendar.AddDays(DateTime.Now, 120001 * 30)); }
// Test the "AddXXX" methods that are common between all calendars. public void TestCalendarAddDays() { long multiplier = TimeSpan.TicksPerDay; DateTime time = DateTime.Now; TimeSpan ts = calendar.AddDays(time, -3) - time; AssertEquals("AddDays (1)", multiplier * -3, ts.Ticks); ts = calendar.AddDays(time, 0) - time; AssertEquals("AddDays (2)", multiplier * 0, ts.Ticks); ts = calendar.AddDays(time, 145) - time; AssertEquals("AddDays (3)", multiplier * 145, ts.Ticks); }
/// <summary> /// Find the next business day with respect to the given date and /// rolling convention. /// </summary> /// <param name="date">The date.</param> /// <param name="businessDayConvention">The business day convention.</param> /// <returns>Returns the resulting <see cref="DateTime"/>.</returns> public DateTime Roll(DateTime date, BusinessDayConventionEnum businessDayConvention) { // QL_REQUIRE(d!=Date(), "Calendar::roll : null date"); DateTime rolledDate = date; if (businessDayConvention == BusinessDayConventionEnum.FOLLOWING || businessDayConvention == BusinessDayConventionEnum.MODFOLLOWING) { while (IsHoliday(rolledDate)) { rolledDate = Calendar.AddDays(rolledDate, 1); } if (businessDayConvention == BusinessDayConventionEnum.MODFOLLOWING && rolledDate.Month != date.Month) { return(Roll(date, BusinessDayConventionEnum.PRECEDING)); } } else if (businessDayConvention == BusinessDayConventionEnum.PRECEDING || businessDayConvention == BusinessDayConventionEnum.MODPRECEDING) { while (IsHoliday(rolledDate)) { rolledDate = Calendar.AddDays(rolledDate, -1); } if (businessDayConvention == BusinessDayConventionEnum.MODPRECEDING && rolledDate.Month != date.Month) { return(Roll(date, BusinessDayConventionEnum.FOLLOWING)); } } else if (businessDayConvention != BusinessDayConventionEnum.NONE) { throw new ArgumentOutOfRangeException(nameof(businessDayConvention), "Unknown rolling convention."); } return(rolledDate); }
/// <summary> /// StartNewDay is a method for starting new day. /// <para> /// First day also start here. /// </para> /// </summary> public void StartNewDay() { if (Ready) { _working = true; RemoveEndedEvents(_today); _today = new DateTime(_today.Year, _today.Month, _today.Day, ActiveHoursStart, ActiveMinutesStart, 0, new GregorianCalendar()); if (!_firstStart) { if (_today.Day == _lastDay.Day && _lastDay.Hour >= ActiveHoursStart && _lastDay.Minute >= ActiveMinutesStart) { _today = _calendar.AddDays(_today, 1); } } _lastDay = _today; _clock.StartClock(); CheckEvent(); if (_firstStart) { FillDaylyEventsList(_today); _firstStart = false; } } else { throw new Exception("Calendar is not initialized"); } }
/// <summary> /// CsvCalcResultで使用するFrom・ToDateに使用 /// ※週を取得する際にSQLiteでは"00~52"で週を計算するのに対して /// こちらはGetWeekOfYearで取得する値が"1~53"なのでここで-1をすることでつじつまを合わせる /// </summary> /// <param name="selectDatetime"></param> /// <returns></returns> private static Dictionary <int, List <DateTime> > WeeklyFormToDaysCalc(DateTime selectDatetime) { var WeeklyNumberDic = new Dictionary <int, List <DateTime> >(); var lastDays = DateTime.DaysInMonth(selectDatetime.Year, selectDatetime.Month); var searchMonth = new DateTime(selectDatetime.Year, selectDatetime.Month, 1); Calendar myCal = CultureInfo.InvariantCulture.Calendar; for (int i = 1; i <= lastDays; i++) { var yearOfWeek = myCal.GetWeekOfYear(searchMonth, CalendarWeekRule.FirstDay, DayOfWeek.Monday) - 1; if (!(WeeklyNumberDic.ContainsKey(yearOfWeek))) { WeeklyNumberDic.Add(yearOfWeek, new List <DateTime>() { searchMonth }); } else { WeeklyNumberDic[yearOfWeek].Add(searchMonth); } searchMonth = myCal.AddDays(searchMonth, 1); } return(WeeklyNumberDic); }
public static async Task <Events> CreateEvent(int event_id, string device_id, string email, string latitude, string longitude, Container container) { Random r = new Random(); Calendar myCal = CultureInfo.InvariantCulture.Calendar; DateTime myDT = DateTime.Now; Events newEvent = new Events { id = event_id.ToString(), event_id = event_id, device_id = device_id, email = email, country = "null", city = null, latitude = latitude, longitude = longitude, is_false_alarm = (r.NextDouble() > 0.5).ToString(), event_details = "Fire", num_of_injured = r.Next(1, 10).ToString(), time = myCal.AddDays(myDT, r.Next(1, 30)) }; Console.WriteLine(newEvent.id.ToString()); try { // Read the item to see if it exists. ItemResponse <Events> newEventResponse = await container.CreateItemAsync <Events>(newEvent, new PartitionKey(newEvent.email)); } catch (CosmosException ex) { Console.WriteLine("Error adding item to events table: {0}\n", ex); } return(newEvent); }
public static void Main() { // Sets a DateTime to April 3, 2002 of the Gregorian calendar. DateTime myDT = new DateTime(2002, 4, 3, new GregorianCalendar()); // Uses the default calendar of the InvariantCulture. Calendar myCal = CultureInfo.InvariantCulture.Calendar; // Displays the values of the DateTime. Console.WriteLine("April 3, 2002 of the Gregorian calendar:"); DisplayValues(myCal, myDT); // Adds 5 to every component of the DateTime. myDT = myCal.AddYears(myDT, 5); myDT = myCal.AddMonths(myDT, 5); myDT = myCal.AddWeeks(myDT, 5); myDT = myCal.AddDays(myDT, 5); myDT = myCal.AddHours(myDT, 5); myDT = myCal.AddMinutes(myDT, 5); myDT = myCal.AddSeconds(myDT, 5); myDT = myCal.AddMilliseconds(myDT, 5); // Displays the values of the DateTime. Console.WriteLine("After adding 5 to each component of the DateTime:"); DisplayValues(myCal, myDT); }
/// <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"); } }
private static DateTime DeferOccurrenceFallingOnWeekend(Calendar calendar, DateTime occurrence, bool skipWeekends = true) { if (skipWeekends) { if (occurrence.DayOfWeek == DayOfWeek.Saturday) { occurrence = calendar.AddDays(occurrence, 2); } if (occurrence.DayOfWeek == DayOfWeek.Sunday) { occurrence = calendar.AddDays(occurrence, 1); } } return(occurrence.ToUniversalTime()); }
private static IEnumerable <DateTime> GetOccurrences(DateInterval interval, DatePeriod period, Calendar calendar, DateTime start, DateTime end, bool skipWeekends = true) { var difference = DateSpan.GetDifference(interval, start, end) / period.Quantifier; if (start.Kind == DateTimeKind.Utc) { start = start.ToLocalTime(); } for (var i = 0; i < difference; i++) { switch (period.Frequency) { case DatePeriodFrequency.Seconds: var seconds = calendar.AddSeconds(start, period.Quantifier * i); yield return(DeferOccurrenceFallingOnWeekend(calendar, seconds, skipWeekends)); break; case DatePeriodFrequency.Minutes: var minutes = calendar.AddMinutes(start, period.Quantifier * i); yield return(DeferOccurrenceFallingOnWeekend(calendar, minutes, skipWeekends)); break; case DatePeriodFrequency.Hours: var hours = calendar.AddHours(start, period.Quantifier * i); yield return(DeferOccurrenceFallingOnWeekend(calendar, hours, skipWeekends)); break; case DatePeriodFrequency.Days: var days = calendar.AddDays(start, period.Quantifier * i); yield return(DeferOccurrenceFallingOnWeekend(calendar, days, skipWeekends)); break; case DatePeriodFrequency.Weeks: var weeks = calendar.AddWeeks(start, period.Quantifier * i); yield return(DeferOccurrenceFallingOnWeekend(calendar, weeks, skipWeekends)); break; case DatePeriodFrequency.Months: var months = calendar.AddMonths(start, period.Quantifier * i); yield return(DeferOccurrenceFallingOnWeekend(calendar, months, skipWeekends)); break; case DatePeriodFrequency.Years: var years = calendar.AddYears(start, period.Quantifier * i); yield return(DeferOccurrenceFallingOnWeekend(calendar, years, skipWeekends)); break; default: throw new ArgumentException("Frequency"); } } }
private static void AddDays(Calendar cal) { int days = 3; Example.time = date1; // <Snippet1> returnTime = DateTime.SpecifyKind(cal.AddDays(time, days), time.Kind); // </Snippet1> Console.WriteLine(returnTime.Kind == time.Kind); }
/// <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); } }
//算日期 public static DateTime getdata(int n, int weeks, int weekday, int y, int r)//年,周次,星期,月,日 { Calendar calendar = CultureInfo.InvariantCulture.Calendar; DateTime starttime = new DateTime(n, y, r); //开学日期 int days; //根据周次,星期算出天数差 days = (weeks - 1) * 7 + weekday; //天数差 DateTime thisdate = calendar.AddDays(starttime, days); //所求日期 return(thisdate); }
/// <summary> /// Succession of the last day of the month /// </summary> /// <param name="value">The subjected value</param> /// <param name="calendar">The calendar on which to base a month</param> /// <returns>Projected DateTime on the corresponding last day of the month</returns> public static DateTime EndOfMonth( this DateTime value, Calendar calendar) { calendar = calendar ?? CultureInfo.CurrentCulture.Calendar; var daysInMonth = calendar.GetDaysInMonth( calendar.GetYear(value), calendar.GetMonth(value), calendar.GetEra(value)); return(calendar.AddDays( value.Date, daysInMonth - calendar.GetDayOfMonth(value))); }
public static Client CreateClient(int i) { Random r = new Random(); Calendar myCal = CultureInfo.InvariantCulture.Calendar; DateTime myDT = DateTime.Now; int password = r.Next(100, 999); string name = GetEmail(); string email = name + i.ToString() + "@gmail.com"; string phone = "050" + r.Next(1000000, 9999999); DateTime time = myCal.AddDays(myDT, r.Next(1, 30)); string color = Colors[r.Next(0, Colors.Count)]; Client newClient = new Client(email, email, password.ToString(), name, phone, time, color); return(newClient); }
public static SmokingDetector CreateDetectors(int device_id, string email) { Random r = new Random(); Calendar myCal = CultureInfo.InvariantCulture.Calendar; DateTime myDT = DateTime.Now; double latitude = Convert.ToInt32(34.86 + Math.Round((r.NextDouble() / 100), 4)); double longitude = Convert.ToInt32(32.5 + Math.Round((r.NextDouble()), 6)); Console.WriteLine(longitude + ", " + latitude + "-------------------------------------------------------------"); string address = "null"; DateTime time = myCal.AddDays(myDT, r.Next(1, 30)); SmokingDetector newDetector = new SmokingDetector(email, device_id.ToString(), email + device_id.ToString(), address, "A", longitude.ToString(), latitude.ToString(), time); return(newDetector); }
private static DateTime OtherDayOfWeek( DateTime value, DayOfWeek target, Calendar calendar, int weekDiff, Func <int, bool> comparerOtherValue) { calendar = calendar ?? CultureInfo.CurrentCulture.Calendar; if (comparerOtherValue(value.DayOfWeek - target)) { value = calendar.AddWeeks(value.Date, weekDiff); } return(calendar.AddDays( value.Date, target - calendar.GetDayOfWeek(value))); }
public static void Schreibe_Kalender(Calendar myCal, DateTime myDT, int Umbruch, int Tag, string text) { for (int i = 0; i < Tag; i++) { if (Umbruch % 7 == 0 && Umbruch != 0) { Console.WriteLine(); } text = myCal.GetDayOfMonth((myCal.AddDays(myDT, i))).ToString(); do { text = " " + text; } while (text.Length != 3); Console.Write(text); Umbruch++; } }
static void Main(string[] args) { //DateTime dateTime = new DateTime(2021,4,3,new GregorianCalendar()); DateTime dateTime = DateTime.Now; Calendar myCal = CultureInfo.InvariantCulture.Calendar; Console.WriteLine("Before adding value in datTime"); DisplayData(myCal, dateTime); dateTime = myCal.AddYears(dateTime, 5); dateTime = myCal.AddMonths(dateTime, 5); dateTime = myCal.AddWeeks(dateTime, 5); dateTime = myCal.AddDays(dateTime, 5); dateTime = myCal.AddHours(dateTime, 5); dateTime = myCal.AddMinutes(dateTime, 5); dateTime = myCal.AddSeconds(dateTime, 5); dateTime = myCal.AddMilliseconds(dateTime, 5); Console.WriteLine(); Console.WriteLine("After adding 5 value in each of this"); DisplayData(myCal, dateTime); Console.ReadLine(); }
public static DateTime Add(this Period thisPeriod, DateTime dateTime) { int periodMultiplierAsInt = thisPeriod.GetPeriodMultiplier(); switch (thisPeriod.period) { case PeriodEnum.D: return(Calendar.AddDays(dateTime, periodMultiplierAsInt)); case PeriodEnum.W: return(Calendar.AddWeeks(dateTime, periodMultiplierAsInt)); case PeriodEnum.M: return(Calendar.AddMonths(dateTime, periodMultiplierAsInt)); case PeriodEnum.Y: return(Calendar.AddYears(dateTime, periodMultiplierAsInt)); default: throw new ArgumentException(string.Format("PeriodEnum '{0}' is not supported in this function", thisPeriod.period)); } }
/// <summary> /// Gets the first day of a week. /// </summary> /// <param name="year">The year.</param> /// <param name="week">The week.</param> /// <param name="calendar">The calendar.</param> /// <param name="calendarWeekRule">The calendar week rule.</param> /// <param name="firstDayOfWeek">The first day of week.</param> /// <returns>The date of the first day in the week.</returns> public static DateTime GetFirstDayOfWeek( int year, int week, Calendar calendar = null, CalendarWeekRule calendarWeekRule = CalendarWeekRule.FirstFourDayWeek, DayOfWeek firstDayOfWeek = DayOfWeek.Sunday) { if (calendar == null) { calendar = CultureInfo.CurrentCulture.Calendar; } DateTime firstDay = new DateTime(year, 1, 7, calendar); while (calendar.GetDayOfWeek(firstDay) != firstDayOfWeek || WeekNumber(firstDay, calendar, calendarWeekRule, firstDayOfWeek) % 52 > 1) { firstDay = calendar.AddDays(firstDay, -1); } // Add the week return((week != 1) ? calendar.AddWeeks(firstDay, week - 1) : firstDay); }
public void ChangeDay(int i) { switch (CurrentViewIndex) { case (int)State.DAILY: lastGivenDate = (calendar.AddDays(lastGivenDate, i)); break; case (int)State.WEEKLY: lastGivenDate = (calendar.AddWeeks(lastGivenDate, i)); break; case (int)State.MONTHLY: lastGivenDate = (calendar.AddMonths(lastGivenDate, i)); break; case (int)State.ILLEGAL: default: break; } RequestView(lastGivenDate); }
public void WriteContents(DateTime specifiedMonth, string targetFileNameAndPath, string[] monthDailyHeader) { try { //Creating Date headers int daysInGivenMonth = DateTime.DaysInMonth(specifiedMonth.Year, specifiedMonth.Month); Calendar myCal = CultureInfo.InvariantCulture.Calendar; for (int i = 0; i < daysInGivenMonth; i++) { monthDailyHeader[i] = specifiedMonth.DayOfWeek + ", " + specifiedMonth.ToString("MMMM") + " " + specifiedMonth.Day + " " + specifiedMonth.Year; specifiedMonth = myCal.AddDays(specifiedMonth, 1); Console.WriteLine(monthDailyHeader[i]); Console.WriteLine("==========================="); Console.WriteLine(""); } } catch (Exception ex) { Console.WriteLine(ex.Message); } return; }
/// <summary> /// Determines if the specified <paramref name="year"/> is a valid year value. /// </summary> /// <param name="year">The year value.</param> /// <param name="cal">The calendar to use.</param> /// <param name="era">The era the year belongs to.</param> /// <returns>true if it's a valid year value; false otherwise.</returns> private static bool IsValidYear(int year, Calendar cal, int era) { int minYear = cal.GetYear(cal.MinSupportedDateTime.Date); int maxYear = cal.GetYear(cal.MaxSupportedDateTime.Date); if (cal.Eras.Length > 1) { DateTime?minDate = null, maxDate = null; DateTime date = cal.MinSupportedDateTime; while (date < cal.MaxSupportedDateTime.Date) { int e = cal.GetEra(date); if (e == era) { if (minDate == null) { minDate = date; } maxDate = date; } date = cal.AddDays(date, 1); } minYear = cal.GetYear(minDate.GetValueOrDefault(cal.MinSupportedDateTime.Date)); maxYear = cal.GetYear(maxDate.GetValueOrDefault(cal.MaxSupportedDateTime.Date)); } year = cal.ToFourDigitYear(year); return(year >= minYear && year <= maxYear); }
/// <summary> /// Handles the <see cref="InputDateTextBox.FinishedEditing"/> event. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">A <see cref="EventArgs"/> that contains the event data.</param> private void InputBoxFinishedEditing(object sender, EventArgs e) { this.inputBox.Visible = false; string inputStr = this.inputBox.Text; int stringLength = inputStr.Length; if (stringLength == 6 || stringLength == 8) { int yearLength = stringLength == 8 ? 4 : 2; string dayString = inputStr.Substring(this.dayPartIndex * 2, 2); string monthString = inputStr.Substring(this.monthPartIndex * 2, 2); string yearString = inputStr.Substring(this.yearPartIndex * 2, yearLength); int year = int.Parse(yearString); Calendar cal = this.datePicker.Picker.CultureCalendar; year = cal.ToFourDigitYear(year); if (IsValidYear(year, cal, cal.GetEra(DateTime.Today)) && IsValidMonth(monthString, year, cal)) { DateTime date = new DateTime(year, int.Parse(monthString), 1, cal); if (IsValidDay(dayString, date, cal)) { this.Date = cal.AddDays(date, int.Parse(dayString) - 1); } } } this.inEditMode = false; this.Focus(); }
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(); }
public static void AddDays_Invalid(Calendar calendar) { Assert.Throws<ArgumentException>(() => calendar.AddDays(calendar.MaxSupportedDateTime, 1)); Assert.Throws<ArgumentException>(() => calendar.AddDays(calendar.MinSupportedDateTime, -1)); Assert.Throws<ArgumentException>(() => calendar.AddDays(DateTime.Now, -120001 * 30)); Assert.Throws<ArgumentException>(() => calendar.AddDays(DateTime.Now, 120001 * 30)); }
public void TestNextValidRandom() { const int numberOfIterations = 10000; // Use to allow sequential testing for easier debugging or average timing const bool parallel = true; Random random = new Random(); Calendar calendar = CultureInfo.CurrentCulture.Calendar; Action <int> testAction = iteration => { // Random initial DateTime int year = random.Next(1, 9999); int month = random.Next(1, 13); int daysInMonth = calendar.GetDaysInMonth(year, month); int day = random.Next(1, daysInMonth); DateTime startDateTime = new DateTime( year, month, day, random.Next(24), random.Next(60), random.Next(60)); // Random incrementation int incrementationType = random.Next(5); string incrementationTypeName; int incrementationAmount; DateTime expectedDateTime; switch (incrementationType) { default: case 0: incrementationTypeName = "Month"; incrementationAmount = random.Next(12 - startDateTime.Month); expectedDateTime = calendar.AddMonths( startDateTime, incrementationAmount); if (incrementationAmount > 0) { expectedDateTime = new DateTime( expectedDateTime.Year, expectedDateTime.Month, 1, 0, 0, 0); } break; case 1: incrementationTypeName = "Day"; incrementationAmount = random.Next(daysInMonth - startDateTime.Day); expectedDateTime = calendar.AddDays( startDateTime, incrementationAmount); if (incrementationAmount > 0) { expectedDateTime = new DateTime( expectedDateTime.Year, expectedDateTime.Month, expectedDateTime.Day, 0, 0, 0); } break; case 2: incrementationTypeName = "Hour"; incrementationAmount = random.Next(24 - startDateTime.Hour); expectedDateTime = calendar.AddHours( startDateTime, incrementationAmount); if (incrementationAmount > 0) { expectedDateTime = new DateTime( expectedDateTime.Year, expectedDateTime.Month, expectedDateTime.Day, expectedDateTime.Hour, 0, 0); } break; case 3: incrementationTypeName = "Minute"; incrementationAmount = random.Next(60 - startDateTime.Minute); expectedDateTime = calendar.AddMinutes( startDateTime, incrementationAmount); if (incrementationAmount > 0) { expectedDateTime = new DateTime( expectedDateTime.Year, expectedDateTime.Month, expectedDateTime.Day, expectedDateTime.Hour, expectedDateTime.Minute, 0); } break; case 4: incrementationTypeName = "Second"; incrementationAmount = random.Next(60 - startDateTime.Second); expectedDateTime = calendar.AddSeconds( startDateTime, incrementationAmount); break; } // Random week start day DayOfWeek weekStartDay; string weekStartDayName; switch (random.Next(7)) { default: case 0: weekStartDayName = "Monday"; weekStartDay = DayOfWeek.Monday; break; case 1: weekStartDayName = "Tuesday"; weekStartDay = DayOfWeek.Tuesday; break; case 2: weekStartDayName = "Wednesday"; weekStartDay = DayOfWeek.Wednesday; break; case 3: weekStartDayName = "Thursday"; weekStartDay = DayOfWeek.Thursday; break; case 4: weekStartDayName = "Friday"; weekStartDay = DayOfWeek.Friday; break; case 5: weekStartDayName = "Saturday"; weekStartDay = DayOfWeek.Saturday; break; case 6: weekStartDayName = "Sunday"; weekStartDay = DayOfWeek.Sunday; break; } if (incrementationAmount > 0) { // Test DateTime resultantDateTime; switch (incrementationType) { default: case 0: resultantDateTime = startDateTime.NextValid( inclusive: true, firstDayOfWeek: weekStartDay, month: Schedule .Months( startDateTime .Month + incrementationAmount), hour: Hour.Every, minute: Minute.Every, second: Second.Every); break; case 1: resultantDateTime = startDateTime.NextValid( inclusive: true, firstDayOfWeek: weekStartDay, day: Schedule .Days( startDateTime .Day + incrementationAmount), hour: Hour.Every, minute: Minute.Every, second: Second.Every); break; case 2: resultantDateTime = startDateTime.NextValid( inclusive: true, firstDayOfWeek: weekStartDay, hour: Schedule .Hours( startDateTime .Hour + incrementationAmount), minute: Minute.Every, second: Second.Every); break; case 3: resultantDateTime = startDateTime.NextValid( inclusive: true, firstDayOfWeek: weekStartDay, minute: Schedule .Minutes( startDateTime .Minute + incrementationAmount), hour: Hour.Every, second: Second.Every); break; case 4: resultantDateTime = startDateTime.NextValid( inclusive: true, firstDayOfWeek: weekStartDay, hour: Hour.Every, minute: Minute.Every, second: Schedule .Seconds( startDateTime .Second + incrementationAmount)); break; } // Report Assert.AreEqual( expectedDateTime, resultantDateTime, string.Format( "Started:<{0}>. Iteration: #{1}, Search: {2} {3} ahead, Week start day: {4}", startDateTime, iteration, incrementationAmount, incrementationAmount > 1 ? incrementationTypeName + "s" : incrementationTypeName, weekStartDayName) ); } }; Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); if (parallel) { Parallel.For(0, numberOfIterations, testAction); } else { for (int iteration = 0; iteration < numberOfIterations; iteration++) { testAction(iteration); } } stopwatch.Stop(); if (parallel) { Trace.WriteLine( string.Format( "{0} random iterations took {1}ms", numberOfIterations, stopwatch.ElapsedMilliseconds)); } else { Trace.WriteLine( string.Format( "{0} random iterations took {1}ms (~{2}ms per iteration)", numberOfIterations, stopwatch.ElapsedMilliseconds, stopwatch.ElapsedMilliseconds / numberOfIterations)); } }
/// <summary> /// Processes a dialog key. /// </summary> /// <param name="keyData">One of the <see cref="System.Windows.Forms.Keys"/> values that represents the key to process.</param> /// <returns>true if the key was processed by the control; otherwise, false.</returns> protected override bool ProcessDialogKey(Keys keyData) { if (keyData == Keys.Left || keyData == Keys.Right) { this.SetDatePart(keyData == Keys.Left ? this.RightToLeft == RightToLeft.No : this.RightToLeft == RightToLeft.Yes); return(true); } Calendar cal = this.datePicker.Picker.CultureCalendar; MonthCalendarDate dt = new MonthCalendarDate(cal, this.currentDate); DateTime date = this.Date; if (keyData == Keys.Up || keyData == Keys.Down) { bool up = keyData == Keys.Up; switch (this.selectedPart) { case SelectedDatePart.Day: { int day = dt.Day + (up ? 1 : -1); int daysInMonth = DateMethods.GetDaysInMonth(dt); if (day > daysInMonth) { day = 1; } else if (day < 1) { day = daysInMonth; } date = new DateTime(dt.Year, dt.Month, day, cal); break; } case SelectedDatePart.Month: { int day = dt.Day; int month = dt.Month + (up ? 1 : -1); int monthsInYear = cal.GetMonthsInYear(dt.Year); if (month > monthsInYear) { month = 1; } else if (month < 1) { month = monthsInYear; } DateTime newDate = new DateTime(dt.Year, month, 1, cal); dt = new MonthCalendarDate(cal, newDate); int daysInMonth = DateMethods.GetDaysInMonth(dt); newDate = daysInMonth < day?cal.AddDays(newDate, daysInMonth - 1) : cal.AddDays(newDate, day - 1); date = newDate; break; } case SelectedDatePart.Year: { int year = dt.Year + (up ? 1 : -1); int minYear = cal.GetYear(this.MinDate); int maxYear = cal.GetYear(this.MaxDate); year = Math.Max(minYear, Math.Min(year, maxYear)); int yearDiff = year - dt.Year; date = cal.AddYears(this.currentDate, yearDiff); break; } } this.Date = date < this.MinDate ? this.MinDate : (date > this.MaxDate ? this.MaxDate : date); this.Refresh(); return(true); } if (keyData == Keys.Home || keyData == Keys.End) { bool first = keyData == Keys.Home; switch (this.selectedPart) { case SelectedDatePart.Day: { date = first ? new DateTime(dt.Year, dt.Month, 1, cal) : new DateTime(dt.Year, dt.Month, DateMethods.GetDaysInMonth(dt), cal); break; } case SelectedDatePart.Month: { int day = dt.Day; date = first ? new DateTime(dt.Year, 1, 1, cal) : new DateTime(dt.Year, cal.GetMonthsInYear(dt.Year), 1, cal); int daysInMonth = DateMethods.GetDaysInMonth(dt); date = day > daysInMonth?cal.AddDays(date, daysInMonth - 1) : cal.AddDays(date, day - 1); break; } case SelectedDatePart.Year: { date = first ? this.MinDate.Date : this.MaxDate.Date; break; } } this.Date = date < this.MinDate ? this.MinDate : (date > this.MaxDate ? this.MaxDate : date); this.Refresh(); return(true); } if (keyData == Keys.Space && !this.inEditMode) { this.datePicker.SwitchPickerState(); return(true); } return(base.ProcessDialogKey(keyData)); }
public void CreateCalendar(SLDocument document) { SLStyle date_style = document.CreateStyle(); /* Date_style is the style which must have the date's cells */ date_style.Alignment.Indent = 5; date_style.Alignment.JustifyLastLine = true; date_style.Alignment.ReadingOrder = SLAlignmentReadingOrderValues.RightToLeft; date_style.Alignment.ShrinkToFit = true; date_style.Alignment.TextRotation = 90; date_style.Font.FontColor = System.Drawing.Color.Black; date_style.Font.FontName = "Gill-Sans"; date_style.Font.FontSize = 12; date_style.Font.Bold = true; date_style.SetBottomBorder(DocumentFormat.OpenXml.Spreadsheet.BorderStyleValues.Thick, System.Drawing.Color.Blue); date_style.Alignment.Horizontal = DocumentFormat.OpenXml.Spreadsheet.HorizontalAlignmentValues.Center; /* Style for separating weeks with a column left and a column right colored in blue */ SLStyle date_column_left_style = document.CreateStyle(); SLStyle date_column_right_style = document.CreateStyle(); date_column_left_style.SetLeftBorder(DocumentFormat.OpenXml.Spreadsheet.BorderStyleValues.Thick, System.Drawing.Color.Blue); date_column_right_style.SetRightBorder(DocumentFormat.OpenXml.Spreadsheet.BorderStyleValues.Thick, System.Drawing.Color.Blue); /* Now I separe the weeks with blue colums, calling the date_column_left_style and the date_column_right_style */ /* divide column from January to the end of April */ document.SetCellStyle("B2", date_column_left_style); // put the column for divide weeks document.SetCellStyle("H2", date_column_right_style); // put the column for divide weeks document.SetCellStyle("O2", date_column_right_style); // put the column for divide weeks document.SetCellStyle("V2", date_column_right_style); // put the column for divide weeks document.SetCellStyle("AC2", date_column_right_style); // put the column for divide weeks document.SetCellStyle("AJ2", date_column_right_style); // put the column for divide weeks document.SetCellStyle("AQ2", date_column_right_style); // put the column for divide weeks document.SetCellStyle("AX2", date_column_right_style); // put the column for divide weeks document.SetCellStyle("BE2", date_column_right_style); // put the column for divide weeks document.SetCellStyle("BL2", date_column_right_style); // put the column for divide weeks document.SetCellStyle("BS2", date_column_right_style); // put the column for divide weeks document.SetCellStyle("BZ2", date_column_right_style); // put the column for divide weeks document.SetCellStyle("CG2", date_column_right_style); // put the column for divide weeks document.SetCellStyle("CN2", date_column_right_style); // put the column for divide weeks document.SetCellStyle("CU2", date_column_right_style); // put the column for divide weeks document.SetCellStyle("DB2", date_column_right_style); // put the column for divide weeks document.SetCellStyle("DI2", date_column_right_style); // put the column for divide weeks document.SetCellStyle("DP2", date_column_right_style); // put the column for divide weeks /* divide column from May to the end of July */ document.SetCellStyle("DQ2", date_column_left_style); // put the column for divide weeks document.SetCellStyle("DX2", date_column_left_style); // put the column for divide weeks document.SetCellStyle("EE2", date_column_left_style); // put the column for divide weeks document.SetCellStyle("EL2", date_column_left_style); // put the column for divide weeks document.SetCellStyle("ES2", date_column_left_style); // put the column for divide weeks document.SetCellStyle("EZ2", date_column_left_style); // put the column for divide weeks document.SetCellStyle("FG2", date_column_left_style); // put the column for divide weeks document.SetCellStyle("FN2", date_column_left_style); // put the column for divide weeks document.SetCellStyle("FU2", date_column_left_style); // put the column for divide weeks document.SetCellStyle("GB2", date_column_left_style); // put the column for divide weeks document.SetCellStyle("GI2", date_column_left_style); // put the column for divide weeks document.SetCellStyle("GP2", date_column_left_style); // put the column for divide weeks document.SetCellStyle("GW2", date_column_left_style); // put the column for divide weeks document.SetCellStyle("HD2", date_column_left_style); // put the column for divide weeks /* divide column from August to the end of November */ document.SetCellStyle("HK2", date_column_left_style); // put the column for divide weeks document.SetCellStyle("HR2", date_column_left_style); // put the column for divide weeks document.SetCellStyle("HY2", date_column_left_style); // put the column for divide weeks document.SetCellStyle("IF2", date_column_left_style); // put the column for divide weeks document.SetCellStyle("IM2", date_column_left_style); // put the column for divide weeks document.SetCellStyle("IT2", date_column_left_style); // put the column for divide weeks document.SetCellStyle("JA2", date_column_left_style); // put the column for divide weeks document.SetCellStyle("JH2", date_column_left_style); // put the column for divide weeks document.SetCellStyle("JO2", date_column_left_style); // put the column for divide weeks document.SetCellStyle("JV2", date_column_left_style); // put the column for divide weeks document.SetCellStyle("KC2", date_column_left_style); // put the column for divide weeks document.SetCellStyle("KJ2", date_column_left_style); // put the column for divide weeks document.SetCellStyle("KQ2", date_column_left_style); // put the column for divide weeks document.SetCellStyle("KX2", date_column_left_style); // put the column for divide weeks document.SetCellStyle("LE2", date_column_left_style); // put the column for divide weeks document.SetCellStyle("LL2", date_column_left_style); // put the column for divide weeks document.SetCellStyle("LS2", date_column_left_style); // put the column for divide weeks /* divide column of December */ document.SetCellStyle("LZ2", date_column_left_style); // put the column for divide weeks document.SetCellStyle("MG2", date_column_left_style); // put the column for divide weeks document.SetCellStyle("MN2", date_column_left_style); // put the column for divide weeks document.SetCellStyle("MU2", date_column_left_style); // put the column for divide weeks document.SetCellStyle("NB2", date_column_right_style); // put the column for divide weeks /* Style for displaing the weeks */ SLStyle week_style = document.CreateStyle(); week_style.Alignment.Indent = 5; week_style.Alignment.Horizontal = DocumentFormat.OpenXml.Spreadsheet.HorizontalAlignmentValues.Center; week_style.Font.FontColor = System.Drawing.Color.Blue; week_style.SetTopBorder(DocumentFormat.OpenXml.Spreadsheet.BorderStyleValues.Thick, System.Drawing.Color.Blue); week_style.SetLeftBorder(DocumentFormat.OpenXml.Spreadsheet.BorderStyleValues.Thick, System.Drawing.Color.Blue); week_style.SetRightBorder(DocumentFormat.OpenXml.Spreadsheet.BorderStyleValues.Thick, System.Drawing.Color.Blue); /* Creation of a calendar which is putted in the sheet */ Calendar myCal = CultureInfo.InvariantCulture.Calendar; DateTime localDateToday = DateTime.Today; string week = "W "; for (int i = 1; i <= 366; i++) // print the sequence of the weeks of a year { int f = 1; /* Print days from January to the end of April */ document.MergeWorksheetCells("B1", "H1"); document.MergeWorksheetCells("I1", "O1"); document.MergeWorksheetCells("P1", "V1"); document.MergeWorksheetCells("W1", "AC1"); document.MergeWorksheetCells("AD1", "AJ1"); document.MergeWorksheetCells("AK1", "AQ1"); document.MergeWorksheetCells("AR1", "AX1"); document.MergeWorksheetCells("AY1", "BE1"); document.MergeWorksheetCells("BF1", "BL1"); document.MergeWorksheetCells("BM1", "BS1"); document.MergeWorksheetCells("BT1", "BZ1"); document.MergeWorksheetCells("CA1", "CG1"); document.MergeWorksheetCells("CH1", "CN1"); document.MergeWorksheetCells("CO1", "CU1"); document.MergeWorksheetCells("CV1", "DB1"); document.MergeWorksheetCells("DC1", "DI1"); document.MergeWorksheetCells("DJ1", "DP1"); /* Print the numbered weeks from January to the end of April */ document.SetCellValue("B1", week + f++.ToString()); document.SetCellValue("I1", week + f++.ToString()); document.SetCellValue("P1", week + f++.ToString()); document.SetCellValue("W1", week + f++.ToString()); document.SetCellValue("AD1", week + f++.ToString()); document.SetCellValue("AK1", week + f++.ToString()); document.SetCellValue("AR1", week + f++.ToString()); document.SetCellValue("AY1", week + f++.ToString()); document.SetCellValue("BF1", week + f++.ToString()); document.SetCellValue("BM1", week + f++.ToString()); document.SetCellValue("BT1", week + f++.ToString()); document.SetCellValue("CA1", week + f++.ToString()); document.SetCellValue("CH1", week + f++.ToString()); document.SetCellValue("CO1", week + f++.ToString()); document.SetCellValue("CV1", week + f++.ToString()); document.SetCellValue("DC1", week + f++.ToString()); document.SetCellValue("DJ1", week + f++.ToString()); /* Print days from May to the end of July */ document.MergeWorksheetCells("DQ1", "DW1"); document.MergeWorksheetCells("DX1", "ED1"); document.MergeWorksheetCells("EE1", "EK1"); document.MergeWorksheetCells("EL1", "ER1"); document.MergeWorksheetCells("ES1", "EY1"); document.MergeWorksheetCells("EZ1", "FF1"); document.MergeWorksheetCells("FG1", "FM1"); document.MergeWorksheetCells("FN1", "FT1"); document.MergeWorksheetCells("FU1", "GA1"); document.MergeWorksheetCells("GB1", "GH1"); document.MergeWorksheetCells("GI1", "GO1"); document.MergeWorksheetCells("GP1", "GV1"); document.MergeWorksheetCells("GW1", "HC1"); document.MergeWorksheetCells("HD1", "HJ1"); /* Print the numbered weeks from May to the end of July */ document.SetCellValue("DQ1", week + f++); document.SetCellValue("DX1", week + f++); document.SetCellValue("EE1", week + f++); document.SetCellValue("EL1", week + f++); document.SetCellValue("ES1", week + f++); document.SetCellValue("EZ1", week + f++); document.SetCellValue("FG1", week + f++); document.SetCellValue("FN1", week + f++); document.SetCellValue("FU1", week + f++); document.SetCellValue("GB1", week + f++); document.SetCellValue("GI1", week + f++); document.SetCellValue("GP1", week + f++); document.SetCellValue("GW1", week + f++); document.SetCellValue("HD1", week + f++); /* Print days from August to the end of November */ document.MergeWorksheetCells("HK1", "HQ1"); document.MergeWorksheetCells("HR1", "HX1"); document.MergeWorksheetCells("HY1", "IE1"); document.MergeWorksheetCells("IF1", "IL1"); document.MergeWorksheetCells("IM1", "IS1"); document.MergeWorksheetCells("IT1", "IZ1"); document.MergeWorksheetCells("JA1", "JG1"); document.MergeWorksheetCells("JH1", "JN1"); document.MergeWorksheetCells("JO1", "JU1"); document.MergeWorksheetCells("JV1", "KB1"); document.MergeWorksheetCells("KC1", "KI1"); document.MergeWorksheetCells("KJ1", "KP1"); document.MergeWorksheetCells("KQ1", "KW1"); document.MergeWorksheetCells("KX1", "LD1"); document.MergeWorksheetCells("LE1", "LK1"); document.MergeWorksheetCells("LL1", "LR1"); document.MergeWorksheetCells("LS1", "LY1"); /* Print the numbered weeks from August to the end of November */ document.SetCellValue("HK1", week + f++); document.SetCellValue("HR1", week + f++); document.SetCellValue("HY1", week + f++); document.SetCellValue("IF1", week + f++); document.SetCellValue("IM1", week + f++); document.SetCellValue("IT1", week + f++); document.SetCellValue("JA1", week + f++); document.SetCellValue("JH1", week + f++); document.SetCellValue("JO1", week + f++); document.SetCellValue("JV1", week + f++); document.SetCellValue("KC1", week + f++); document.SetCellValue("KJ1", week + f++); document.SetCellValue("KQ1", week + f++); document.SetCellValue("KX1", week + f++); document.SetCellValue("LE1", week + f++); document.SetCellValue("LL1", week + f++); document.SetCellValue("LS1", week + f++); /* Print days of December */ document.MergeWorksheetCells("LZ1", "MF1"); document.MergeWorksheetCells("MG1", "MM1"); document.MergeWorksheetCells("MN1", "MT1"); document.MergeWorksheetCells("MU1", "NB1"); /* Print the numbered weeks of December */ document.SetCellValue("LZ1", week + f++); document.SetCellValue("MG1", week + f++); document.SetCellValue("MN1", week + f++); document.SetCellValue("MU1", week + f++); DateTime myDT = new DateTime(localDateToday.Year - 1, 12, 30, new GregorianCalendar()); // for show the complete current year // IDK why if I want to show the first of january on cell B2 I must set calendar two day before ??? document.SetCellStyle(2, i, date_style); document.SetCellStyle(1, i, week_style); document.SetCellValue("A2", " "); myDT = myCal.AddDays(myDT, i); var PrintDays = document.SetCellValue(2, i, myDT.Day + "/" + myDT.Month + "/" + myDT.Year); } localDateToday = myCal.AddDays(localDateToday, +1).Date; }
/// <summary> /// Handles the <see cref="InputDateTextBox.FinishedEditing"/> event. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">A <see cref="EventArgs"/> that contains the event data.</param> private void InputBoxFinishedEditing(object sender, EventArgs e) { this.inputBox.Visible = false; string inputStr = this.inputBox.GetCurrentText(); bool containsSeparator = inputStr.Contains(this.datePicker.FormatProvider.DateSeparator); string aggregate = string.Empty; Dictionary <int, string> dic; if (containsSeparator) { aggregate = this.datePicker.FormatProvider.DateSeparator; dic = new Dictionary <int, string> { { this.yearPartIndex, @"(?<year>\d{2,4})" }, { this.dayPartIndex, @"(?<day>\d\d?)" }, { this.monthPartIndex, @"(?<month>\d\d?)" } }; } else { var yearLength = inputStr.Length == 8 ? 4 : 2; dic = new Dictionary <int, string> { { this.yearPartIndex, string.Format(@"(?<year>\d{{{0}}})", yearLength) }, { this.dayPartIndex, @"(?<day>\d\d)" }, { this.monthPartIndex, @"(?<month>\d\d)" } }; } var sortedKeys = dic.Keys.ToList(); sortedKeys.Sort(); var regexPattern = sortedKeys.ConvertAll(i => dic [i]).Aggregate((s1, s2) => s1 + aggregate + s2); var match = System.Text.RegularExpressions.Regex.Match(inputStr, regexPattern); var groups = match.Groups; var dayString = groups ["day"].Value; var monthString = groups ["month"].Value; var yearString = groups ["year"].Value; if (match.Success && !string.IsNullOrEmpty(dayString) && !string.IsNullOrEmpty(monthString) && !string.IsNullOrEmpty(yearString)) { int year = int.Parse(yearString); Calendar cal = this.datePicker.Picker.CultureCalendar; year = cal.ToFourDigitYear(year); if (IsValidYear(year, cal, cal.GetEra(DateTime.Today)) && IsValidMonth(monthString, year, cal)) { DateTime date = new DateTime(year, int.Parse(monthString), 1, cal); if (IsValidDay(dayString, date, cal)) { this.Date = cal.AddDays(date, int.Parse(dayString) - 1); } } } this.inEditMode = false; this.Focus(); }