private void SetMonthModeCalendarDayButtons() { DateTime firstDayOfMonth = DateTimeHelper.DiscardDayTime(DisplayDate); int lastMonthToDisplay = GetNumberOfDisplayedDaysFromPreviousMonth(firstDayOfMonth); bool isMinMonth = DateTimeHelper.CompareYearMonth(firstDayOfMonth, DateTime.MinValue) <= 0; bool isMaxMonth = DateTimeHelper.CompareYearMonth(firstDayOfMonth, DateTime.MaxValue) >= 0; int daysInMonth = _calendar.GetDaysInMonth(firstDayOfMonth.Year, firstDayOfMonth.Month); CultureInfo culture = DateTimeHelper.GetCulture(this); int count = ROWS * COLS; for (int childIndex = COLS; childIndex < count; childIndex++) { CalendarDayButton childButton = _monthView.Children[childIndex] as CalendarDayButton; Debug.Assert(childButton != null); int dayOffset = childIndex - lastMonthToDisplay - COLS; if ((!isMinMonth || (dayOffset >= 0)) && (!isMaxMonth || (dayOffset < daysInMonth))) { DateTime dateToAdd = _calendar.AddDays(firstDayOfMonth, dayOffset); SetMonthModeDayButtonState(childButton, dateToAdd); childButton.DataContext = dateToAdd; childButton.SetContentInternal(DateTimeHelper.ToDayString(dateToAdd, culture)); } else { SetMonthModeDayButtonState(childButton, null); childButton.DataContext = null; childButton.SetContentInternal(DateTimeHelper.ToDayString(null, culture)); } } }
/// <summary> /// Initializes a new instance of <see cref="Age"/>. /// </summary> /// <param name="start">The date and time when the age started.</param> /// <param name="end">The date and time when the age ended.</param> /// <param name="calendar">Calendar used to calculate age.</param> public Age(DateTime start, DateTime end, Calendar calendar) { if (start > end) throw new ArgumentException("The starting date cannot be later than the end date."); var startDate = start.Date; var endDate = end.Date; _years = _months = _days = 0; _days += calendar.GetDayOfMonth(endDate) - calendar.GetDayOfMonth(startDate); if (_days < 0) { _days += calendar.GetDaysInMonth(calendar.GetYear(startDate), calendar.GetMonth(startDate)); _months--; } _months += calendar.GetMonth(endDate) - calendar.GetMonth(startDate); if (_months < 0) { _months += calendar.GetMonthsInYear(calendar.GetYear(startDate)); _years--; } _years += calendar.GetYear(endDate) - calendar.GetYear(startDate); var ts = endDate.Subtract(startDate); _totalDays = (Int32)ts.TotalDays; }
/// <summary> /// Checks that each day from the given start year to the end year (inclusive) is equal /// between the BCL and the Noda Time calendar. Additionally, the number of days in each month and year /// and the number of months (and leap year status) in each year is checked. /// </summary> internal static void AssertEquivalent(Calendar bcl, CalendarSystem noda, int fromYear, int toYear) { // We avoid asking the BCL to create a DateTime on each iteration, simply // because the BCL implementation is so slow. Instead, we just check at the start of each month that // we're at the date we expect. DateTime bclDate = bcl.ToDateTime(fromYear, 1, 1, 0, 0, 0, 0); for (int year = fromYear; year <= toYear; year++) { Assert.AreEqual(bcl.GetDaysInYear(year), noda.GetDaysInYear(year), "Year: {0}", year); Assert.AreEqual(bcl.GetMonthsInYear(year), noda.GetMonthsInYear(year), "Year: {0}", year); for (int month = 1; month <= noda.GetMonthsInYear(year); month++) { // Sanity check at the start of each month. Even this is surprisingly slow. // (These three tests make up about 20% of the total execution time for the test.) Assert.AreEqual(year, bcl.GetYear(bclDate)); Assert.AreEqual(month, bcl.GetMonth(bclDate)); Assert.AreEqual(1, bcl.GetDayOfMonth(bclDate)); Assert.AreEqual(bcl.GetDaysInMonth(year, month), noda.GetDaysInMonth(year, month), "Year: {0}; Month: {1}", year, month); Assert.AreEqual(bcl.IsLeapYear(year), noda.IsLeapYear(year), "Year: {0}", year); for (int day = 1; day <= noda.GetDaysInMonth(year, month); day++) { LocalDate nodaDate = new LocalDate(year, month, day, noda); Assert.AreEqual(bclDate, nodaDate.ToDateTimeUnspecified(), "Original calendar system date: {0:yyyy-MM-dd}", nodaDate); Assert.AreEqual(nodaDate, LocalDate.FromDateTime(bclDate, noda)); Assert.AreEqual(year, nodaDate.Year); Assert.AreEqual(month, nodaDate.Month); Assert.AreEqual(day, nodaDate.Day); bclDate = bclDate.AddDays(1); } } } }
public void ShiftDay(int amount) { int day = _day + amount; int month = _month; int year = _year; int daysInMonth; if (day <= 0) { month--; if (month < 1) { year--; month = 12; } daysInMonth = _myCal.GetDaysInMonth(year, month); day = daysInMonth + day; } else if (day > _numberOfDaysInMonth) { month++; if (month > 12) { year++; month = 1; } day = day - _numberOfDaysInMonth; } _day = day; _month = month; _year = year; InitModel(); }
// ---------------------------------------------------------------------- public static TimeSpan Month( Calendar calendar, int year, YearMonth yearMonth ) { return Days( calendar.GetDaysInMonth( year, (int)yearMonth ) ); }
private void BuildCalendarUI() { int iDaysInMonth = sysCal.GetDaysInMonth(_DisplayStartDate.Year, _DisplayStartDate.Month); int iOffsetDays = System.Convert.ToInt32(System.Enum.ToObject(typeof(System.DayOfWeek), _DisplayStartDate.DayOfWeek)); int iWeekCount = 0; WeekOfDaysControls weekRowCtrl = new WeekOfDaysControls(); MonthViewGrid.Children.Clear(); AddRowsToMonthGrid(iDaysInMonth, iOffsetDays); MonthYearLabel.Content = months.ElementAt(_DisplayMonth - 1) + " " + _DisplayYear; for (int i = 1; i <= iDaysInMonth; i++) { if ((i != 1) && System.Math.IEEERemainder((i + iOffsetDays - 1), 7) == 0) { // -- add existing weekrowcontrol to the monthgrid Grid.SetRow(weekRowCtrl, iWeekCount); MonthViewGrid.Children.Add(weekRowCtrl); // -- make a new weekrowcontrol weekRowCtrl = new WeekOfDaysControls(); iWeekCount += 1; } // -- load each weekrow with a DayBoxControl whose label is set to day number DayBoxControl dayBox = new DayBoxControl(i); dayBox.DayNumberLabel.Content = i.ToString(); dayBox.Tag = i; dayBox.MouseDoubleClick += DayBox_DoubleClick; dayBox.DragEnter += DayBox_DragEnter; // -- customize daybox for today: if ((new DateTime(_DisplayYear, _DisplayMonth, i)) == DateTime.Today) { dayBox.DayLabelRowBorder.Background = (Brush)dayBox.TryFindResource("OrangeGradientBrush"); dayBox.DayAppointmentsStack.Background = Brushes.Wheat; } if (_monthAppointments != null) { int iday = i; Predicate <Vacation> aptFind = delegate(Vacation apt) { return((int)apt.m_curDate.Day == iday); }; List <Vacation> aptInDay = _monthAppointments.FindAll(aptFind); foreach (Vacation a in aptInDay) { DayBoxAppointmentControl apt = new DayBoxAppointmentControl(); apt.SetDoctor(a.m_doctor); apt.m_startDate = a.m_startDate; apt.m_endDate = a.m_endDate; apt.DisplayText.Text = a.m_doctor + " vacation until: " + a.m_endDate.ToString("d"); apt.Foreground = new SolidColorBrush(Color.FromRgb(255, 255, 255)); apt.MouseDoubleClick += Appointment_DoubleClick; dayBox.DayAppointmentsStack.Children.Add(apt); } } Grid.SetColumn(dayBox, (i - (iWeekCount * 7)) + iOffsetDays); weekRowCtrl.WeekRowGrid.Children.Add(dayBox); } Grid.SetRow(weekRowCtrl, iWeekCount); MonthViewGrid.Children.Add(weekRowCtrl); }
private static DateTime? GetDateInfo(string[] dateSplit, int start, int num, Calendar calendar) { string year = string.Empty; string month = string.Empty; string day = string.Empty; bool bc = false; DateTime? ret = null; CultureInfo culture = System.Globalization.CultureInfo.CurrentCulture; // only parse if we have the expected number of date parts if (! (start != 0 && num == 3 && (dateSplit.Length < start + num))) { if (num == 1) { // year only year = dateSplit[start]; bc = false; if (year.EndsWith("B.C.", true, culture)) { bc = true; year = year.Substring(0, year.Length - "B.C.".Length); } } else if (num == 2) { // month month = dateSplit[start]; // year year = dateSplit[start + 1]; bc = false; if (year.EndsWith("B.C.", true, culture)) { bc = true; year = year.Substring(0, year.Length - "B.C.".Length); } } else if (num == 3) { // day day = dateSplit[start]; // month month = dateSplit[start + 1]; // year year = dateSplit[start + 2]; bc = false; if (year.EndsWith("B.C.", true, culture)) { bc = true; year = year.Substring(0, year.Length - "B.C.".Length); } } int y = 1; int m = 1; int d = 1; if ((!int.TryParse(month, out m)) && month != string.Empty) { // month name, find month number foreach (string[] names in _monthNames) { int i = 1; bool match = false; foreach (string monthName in names) { if (string.Compare(monthName, month, true) == 0) { match = true; break; } i ++; } if (match) { m = i; break; } } } int.TryParse(day, out d); // year could be of the form 1980/81 // have 2 datetimes for each date ? // only having 1 won't lose the data, could prevent proper merge // though as the DateTime will be used for comparison if (year.IndexOf('/') != -1) { year = year.Substring(0, year.IndexOf('/')); } // if we have the month as > 12 then must be mm dd yyyy // and not dd mm yyyy if (m > 12) { int tmp = d; d = m; m = tmp; } if (int.TryParse(year, out y)) { if (m == 0) { m = 1; } if (d == 0) { d = 1; } if (y == 0) { y = 1; } // ignore era, dates won't be bc, no way to get info back // that far reliably so shouldn't be an issue // try and correct for invalid dates, such as // in presidents.ged with 29 FEB 1634/35 int daysInMonth = 0; if (m > 0 && m <= 12 && y > 0 && y < 9999) { daysInMonth = calendar.GetDaysInMonth(y, m); if (d > daysInMonth) { d = daysInMonth; } } try { ret = new DateTime(y, m, d, calendar); } catch { // if we fail to parse not much we can do, // just don't provide a datetime } } } return ret; }
public void TestDaysInYear (Calendar calendar, int year) { var daysInYear = calendar.GetDaysInYear (year); var daysInMonths = 0; var monthInYear = calendar.GetMonthsInYear (year); for (var m = 1; m <= monthInYear; m++) daysInMonths += calendar.GetDaysInMonth (year, m); Assert.AreEqual (daysInYear, daysInMonths, string.Format("Calendar:{0} Year:{1}",calendar.GetType(), year)); }
/// <summary> /// 构造日历界面 /// </summary> private void BuildCalendarUI() { //返回指定月份的总天数 int daysInMonth = _cultureCalendar.GetDaysInMonth(_displayStartDate.Year, _displayStartDate.Month); //返回展示日期的星期数 _startDayOffset = (int)Enum.ToObject(typeof(DayOfWeek), _displayStartDate.DayOfWeek); //总周数 int weekCount = 0; var weekRowCtrl = new WeekControl(); GrdMonthView.Children.Clear(); SetMonthGridRowDefinition(daysInMonth, _startDayOffset); LblMonth.Content = string.Format("{0}年{1}月", _displayYear, _displayMonth); for (int i = 1; i <= daysInMonth; i++) { //算出是星期几 int week = (i + _startDayOffset - 1) % 7; //因为第一次已经有周控件了,所以i != 1 if ((i != 1) && (0 == week)) { //开始新一周,将上周的控件加入 Grid.SetRow(weekRowCtrl, weekCount); GrdMonthView.Children.Add(weekRowCtrl); weekRowCtrl = new WeekControl(); weekCount += 1; } //添加日控件 var dayControl = new DayControl { LblDayNumber = { Content = i.ToString(CultureInfo.InvariantCulture) }, Tag = i }; dayControl.MouseDoubleClick += DayControl_DoubleClick; //如果为当天,设置不同的样式 if (new DateTime(_displayYear, _displayMonth, i) == DateTime.Today) { dayControl.BdrDayLabel.Background = (Brush)dayControl.TryFindResource("TodayBrush"); dayControl.SplDateTimeEvents.Background = Brushes.Wheat; } int iday = i; if (DateTimeEventControlFactory != null) { var eventsInDay = from e in _dateTimeEvents where DayEqual(e.HappenTime, DisplayStartDate.AddDays(iday - 1)) select e; foreach (var e in eventsInDay) { var control = DateTimeEventControlFactory.GetControl(e); if (control != null) { dayControl.SplDateTimeEvents.Children.Add(control.EventControl); } } } Grid.SetColumn(dayControl, (i - (weekCount * 7)) + _startDayOffset); weekRowCtrl.GrdWeek.Children.Add(dayControl); } //加入最后一周 Grid.SetRow(weekRowCtrl, weekCount); GrdMonthView.Children.Add(weekRowCtrl); }
/// <summary> /// Get's the next valid second after the current . /// </summary> /// <param name="dateTime">The date time (fractions of a second are removed).</param> /// <param name="month">The month.</param> /// <param name="week">The week.</param> /// <param name="day">The day.</param> /// <param name="weekDay">The week day.</param> /// <param name="hour">The hour.</param> /// <param name="minute">The minute.</param> /// <param name="second">The second.</param> /// <param name="calendar">The calendar.</param> /// <param name="calendarWeekRule">The calendar week rule.</param> /// <param name="firstDayOfWeek">The first day of week.</param> /// <param name="inclusive">if set to <c>true</c> can return the time specified, otherwise, starts at the next second..</param> /// <returns> /// The next valid date (or <see cref="DateTime.MaxValue"/> if none). /// </returns> public static DateTime NextValid( this DateTime dateTime, Month month = Month.Every, Week week = Week.Every, Day day = Day.Every, WeekDay weekDay = WeekDay.Every, Hour hour = Hour.Zeroth, Minute minute = Minute.Zeroth, Second second = Second.Zeroth, Calendar calendar = null, CalendarWeekRule calendarWeekRule = CalendarWeekRule.FirstFourDayWeek, DayOfWeek firstDayOfWeek = DayOfWeek.Sunday, bool inclusive = false) { // Never case, if any are set to never, we'll never get a valid date. if ((month == Month.Never) || (week == Week.Never) || (day == Day.Never) || (weekDay == WeekDay.Never) || (hour == Hour.Never) || (minute == Minute.Never) || (second == Second.Never)) return DateTime.MaxValue; if (calendar == null) calendar = CultureInfo.CurrentCulture.Calendar; // Set the time to this second (or the next one if not inclusive), remove fractions of a second. dateTime = new DateTime( dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second); if (!inclusive) dateTime = calendar.AddSeconds(dateTime, 1); // Every second case. if ((month == Month.Every) && (day == Day.Every) && (weekDay == WeekDay.Every) && (hour == Hour.Every) && (minute == Minute.Every) && (second == Second.Every) && (week == Week.Every)) return calendar.AddSeconds(dateTime, 1); // Get days and months. IEnumerable<int> days = day.Days().OrderBy(dy => dy); IEnumerable<int> months = month.Months(); // Remove months where the first day isn't in the month. int firstDay = days.First(); if (firstDay > 28) { // 2000 is a leap year, so February has 29 days. months = months.Where(mn => calendar.GetDaysInMonth(2000, mn) >= firstDay); if (months.Count() < 1) return DateTime.MaxValue; } // Get remaining date components. int y = calendar.GetYear(dateTime); int m = calendar.GetMonth(dateTime); int d = calendar.GetDayOfMonth(dateTime); int h = calendar.GetHour(dateTime); int n = calendar.GetMinute(dateTime); int s = calendar.GetSecond(dateTime); IEnumerable<int> weeks = week.Weeks(); IEnumerable<DayOfWeek> weekDays = weekDay.WeekDays(); IEnumerable<int> hours = hour.Hours().OrderBy(i => i); IEnumerable<int> minutes = minute.Minutes().OrderBy(i => i); IEnumerable<int> seconds = second.Seconds(); do { foreach (int currentMonth in months) { if (currentMonth < m) continue; if (currentMonth > m) { d = 1; h = n = s = 0; } m = currentMonth; foreach (int currentDay in days) { if (currentDay < d) continue; if (currentDay > d) h = n = s = 0; d = currentDay; // Check day is valid for this month. if ((d > 28) && (d > calendar.GetDaysInMonth(y, m))) break; // We have a potential day, check week and week day dateTime = new DateTime(y, m, d, h, n, s); if ((week != Week.Every) && (!weeks.Contains(dateTime.WeekNumber(calendar, calendarWeekRule, firstDayOfWeek)))) continue; if ((weekDay != WeekDay.Every) && (!weekDays.Contains(calendar.GetDayOfWeek(dateTime)))) continue; // We have a date match, check time. foreach (int currentHour in hours) { if (currentHour < h) continue; if (currentHour > h) n = s = 0; h = currentHour; foreach (int currentMinute in minutes) { if (currentMinute < n) continue; if (currentMinute > n) s = 0; n = currentMinute; foreach (int currentSecond in seconds) { if (currentSecond < s) continue; return new DateTime(y, m, d, h, n, currentSecond, calendar); } n = s = 0; } h = n = s = 0; } d = 1; } d = 1; h = n = s = 0; } y++; // Don't bother checking max year. if (y > 9998) return DateTime.MaxValue; // Start next year m = d = 1; h = n = s = 0; } while (true); }
private void BuildCalendarUI() { int iDaysInMonth = sysCal.GetDaysInMonth(_DisplayStartDate.Year, _DisplayStartDate.Month); int iOffsetDays = Convert.ToInt32(System.Enum.ToObject(typeof(System.DayOfWeek), _DisplayStartDate.DayOfWeek)); int iWeekCount = 0; WeekOfDaysControl weekRowCtrl = new WeekOfDaysControl(); MonthViewGrid.Children.Clear(); AddRowsToMonthGrid(iDaysInMonth, iOffsetDays); MonthYearLabel.Content = (new DateTimeFormatInfo()).GetMonthName(_DisplayMonth) + " " + _DisplayYear; //CultureInfo.CurrentUICulture.DateTimeFormat.MonthNames[i] for (int i = 1; i <= iDaysInMonth; i++) { if ((i != 1) && System.Math.IEEERemainder((i + iOffsetDays - 1), 7) == 0) { //-- add existing weekrowcontrol to the monthgrid Grid.SetRow(weekRowCtrl, iWeekCount); MonthViewGrid.Children.Add(weekRowCtrl); //-- make a new weekrowcontrol weekRowCtrl = new WeekOfDaysControl(); iWeekCount += 1; } //-- load each weekrow with a DayBoxControl whose label is set to day number DayBoxControl dayBox = new DayBoxControl(); dayBox.DayNumberLabel.Content = i.ToString(); dayBox.Tag = i; dayBox.MouseDoubleClick += DayBox_DoubleClick; //-- customize daybox for today: if ((new System.DateTime(_DisplayYear, _DisplayMonth, i)) == System.DateTime.Today) { dayBox.DayLabelRowBorder.Background = (Brush)dayBox.TryFindResource("OrangeGradientBrush"); dayBox.DayAppointmentsStack.Background = Brushes.Wheat; } //-- for design mode, add appointments to random days for show... if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(this)) { if (Math.Round(1d) < 0.25) { DayBoxAppointmentControl apt = new DayBoxAppointmentControl(); apt.DisplayText.Text = "Apt on " + i + "th"; dayBox.DayAppointmentsStack.Children.Add(apt); } } else if (_monthAppointments != null) { //-- Compiler warning about unpredictable results if using i (the iterator) in lambda, the // "hint" suggests declaring another var and set equal to iterator var int iday = i; List <Appointment> aptInDay = _monthAppointments.FindAll(new System.Predicate <Appointment>((Appointment apt) => Convert.ToDateTime(apt.StartTime).Day == iday)); foreach (Appointment a in aptInDay) { DayBoxAppointmentControl apt = new DayBoxAppointmentControl(); apt.DisplayText.Text = a.Subject; apt.Tag = a.AppointmentID; apt.MouseDoubleClick += Appointment_DoubleClick; dayBox.DayAppointmentsStack.Children.Add(apt); } } Grid.SetColumn(dayBox, (i - (iWeekCount * 7)) + iOffsetDays); weekRowCtrl.WeekRowGrid.Children.Add(dayBox); } Grid.SetRow(weekRowCtrl, iWeekCount); MonthViewGrid.Children.Add(weekRowCtrl); }
public void BuildCalendarUI() { displayDate = DateTime.Now.AddDays(-1 * (DateTime.Now.Day - 1)); displayMonth = displayDate.Month; displayYear = displayDate.Year; cultureInfo = new CultureInfo(CultureInfo.CurrentUICulture.LCID); sysCal = cultureInfo.Calendar; int iDaysInMonth = sysCal.GetDaysInMonth(displayDate.Year, displayDate.Month); iOffsetDays = (int)displayDate.DayOfWeek; int iWeekCount = 0; var weekControl = new DaysOfWeekControl(); MonthViewGrid.Children.Clear(); AddRowsToMonthGrid(iDaysInMonth, iOffsetDays); switch (displayDate.Month) { case 1: MonthYearLabel.Content = "January" + " " + displayYear; break; case 2: MonthYearLabel.Content = "February" + " " + displayYear; break; case 3: MonthYearLabel.Content = "March" + " " + displayYear; break; case 4: MonthYearLabel.Content = "April" + " " + displayYear; break; case 5: MonthYearLabel.Content = "May" + " " + displayYear; break; case 6: MonthYearLabel.Content = "June" + " " + displayYear; break; case 7: MonthYearLabel.Content = "July" + " " + displayYear; break; case 8: MonthYearLabel.Content = "August" + " " + displayYear; break; case 9: MonthYearLabel.Content = "September" + " " + displayYear; break; case 10: MonthYearLabel.Content = "October" + " " + displayYear; break; case 11: MonthYearLabel.Content = "November" + " " + displayYear; break; case 12: MonthYearLabel.Content = "December" + " " + displayYear; break; } for (int i = 1; i <= iDaysInMonth; i++) { if ((i != 1) && ((i + iOffsetDays - 1) % 7 == 0)) { //Add existing weekrow to month Grid Grid.SetRow(weekControl, iWeekCount); MonthViewGrid.Children.Add(weekControl); //Add new Week Row Control weekControl = new DaysOfWeekControl(); iWeekCount += 1; } //load each weekrow with a DayBoxControl whose label is set to day number var dayBox = new DayBoxControl(); dayBox.DayNumberLabel.Content = i.ToString(); dayBox.Tag = i; //Customize DayBox for today if (new DateTime(displayYear, displayMonth, i) == DateTime.Today) { dayBox.DayNumberLabel.Background = dayBox.TryFindResource("OrangeGradientBrush") as Brush; } DateTime iday = new DateTime(displayYear,displayMonth,i); List<ECCAppointment> aptList = StudioRepository.GetAppointmentDayFromRepository(iday).ToList(); if(aptList.Count > 0) { foreach (var item in aptList) { DayBoxAppointmentControl apt = new DayBoxAppointmentControl(); apt.DisplayText.Text = item.AppointmentName; apt.datetxtBlk.Text = iday.ToString(); dayBox.DayAppointmentsStack.Children.Add(apt); } } Grid.SetColumn(dayBox, (i - (iWeekCount * 7) + iOffsetDays)); weekControl.WeekRowGrid.Children.Add(dayBox); } Grid.SetRow(weekControl, iWeekCount); MonthViewGrid.Children.Add(weekControl); }
// ---------------------------------------------------------------------- // extract of DateDiff.CalcYears() private static int YearDiff( DateTime date1, DateTime date2, Calendar calendar ) { if ( date1.Equals( date2 ) ) { return 0; } int year1 = calendar.GetYear( date1 ); int month1 = calendar.GetMonth( date1 ); int year2 = calendar.GetYear( date2 ); int month2 = calendar.GetMonth( date2 ); // find the the day to compare int compareDay = date2.Day; int compareDaysPerMonth = calendar.GetDaysInMonth( year1, month1 ); if ( compareDay > compareDaysPerMonth ) { compareDay = compareDaysPerMonth; } // build the compare date DateTime compareDate = new DateTime( year1, month2, compareDay, date2.Hour, date2.Minute, date2.Second, date2.Millisecond ); if ( date2 > date1 ) { if ( compareDate < date1 ) { compareDate = compareDate.AddYears( 1 ); } } else { if ( compareDate > date1 ) { compareDate = compareDate.AddYears( -1 ); } } return year2 - calendar.GetYear( compareDate ); }