GetYear() public abstract method

public abstract GetYear ( DateTime time ) : int
time DateTime
return int
Ejemplo n.º 1
0
        /// <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;
        }
Ejemplo n.º 2
0
        public virtual DateTime GetToDate(DateTime dt, System.Globalization.Calendar calendar)
        {
            if (this.Order == 1 && this.FromMonth > this.ToMonth)
            {
                if (calendar.GetMonth(dt) == 12)
                {
                    //در اولین بازه محدوده، ماه شروع در سال قبل قرار گرفته
                    dt = calendar.AddYears(dt, 1);
                }
            }
            if (this.Order == 12 && this.FromMonth > this.ToMonth)
            {
                if (calendar.GetMonth(dt) == 12)
                {
                    //در آخرین بازه محدوده، ماه پایان در سال بعد قرار گرفته
                    dt = calendar.AddYears(dt, 1);
                }
            }
            else if (this.Order == 0 && this.FromMonth >= this.ToMonth)
            {
                //بازه سالانه است و پایان در سال بعد قرار گرفته
                dt = calendar.AddYears(dt, 1);
            }

            if (calendar is PersianCalendar)
            {
                if (calendar.IsLeapYear(calendar.GetYear(dt)) && this.ToMonth == 12 && this.ToDay == 29)
                {
                    return(calendar.ToDateTime(calendar.GetYear(dt), this.ToMonth, 30, 0, 0, 0, 0));
                }
                else
                {
                    return(calendar.ToDateTime(calendar.GetYear(dt), this.ToMonth, this.ToDay, 0, 0, 0, 0));
                }
            }
            else
            {
                if (calendar.IsLeapYear(dt.Year) && this.ToMonth == 2 && this.ToDay == 28)
                {
                    //اگر سال کبسه بود و برای ماه فوریه روز 28 انتخاب شده بود
                    //به صورت خودکار با روز 29 جایگزین می شود
                    return(calendar.ToDateTime(dt.Year, this.ToMonth, 29, 0, 0, 0, 0));
                }
                else
                {
                    return(calendar.ToDateTime(dt.Year, this.ToMonth, this.ToDay, 0, 0, 0, 0));
                }
            }
        }
Ejemplo n.º 3
0
 private string GetDateInCalendar(System.Globalization.Calendar calendar, DateTime dateTime)
 {
     return(string.Format("{0:0000}/{1:00}/{2:00}",
                          calendar.GetYear(dateTime),
                          calendar.GetMonth(dateTime),
                          calendar.GetDayOfMonth(dateTime)));
 }
Ejemplo n.º 4
0
        /// <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);
                    }
                }
            }
        }
Ejemplo n.º 5
0
        public DateTimePickerControl()
        {
            InitializeComponent();

            monthNumber = currentCalendar.GetMonth(DateTime.Today);
            yearNumber  = currentCalendar.GetYear(DateTime.Today);

            var months = CultureInfo.CurrentCulture.DateTimeFormat.MonthNames;

            Array.Resize <string>(ref months, 12);
            monthBox.ItemsSource = months;

            yearBox.Text = $"{currentCalendar.GetYear(SelectedDate)}";

            monthBox.SelectedIndex = monthNumber - 1;
            Update();
        }
Ejemplo n.º 6
0
 private string GetDateTimeInPersianCalendar(DateTime dateTime)
 {
     return(string.Format("{0:0000}/{1:00}/{2:00}-{3:00}:{4:00}",
                          PersianCalendar.GetYear(dateTime),
                          PersianCalendar.GetMonth(dateTime),
                          PersianCalendar.GetDayOfMonth(dateTime),
                          PersianCalendar.GetHour(dateTime), PersianCalendar.GetMinute(dateTime)));
 }
Ejemplo n.º 7
0
        // Token: 0x06002F19 RID: 12057 RVA: 0x000B4AF4 File Offset: 0x000B2CF4
        internal void TimeToLunar(DateTime time, ref int year, ref int month, ref int day)
        {
            Calendar defaultInstance = GregorianCalendar.GetDefaultInstance();
            int      year2           = defaultInstance.GetYear(time);
            int      month2          = defaultInstance.GetMonth(time);
            int      dayOfMonth      = defaultInstance.GetDayOfMonth(time);

            this.GregorianToLunar(year2, month2, dayOfMonth, ref year, ref month, ref day);
        }
Ejemplo n.º 8
0
        private void RedirectToCurrentWeek()
        {
            DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;

            System.Globalization.Calendar cal = dfi.Calendar;
            int currentWeek = cal.GetWeekOfYear(DateTime.Now, dfi.CalendarWeekRule, dfi.FirstDayOfWeek);
            int currentYear = cal.GetYear(DateTime.Now);

            Response.Redirect("skema.aspx?aar=" + currentYear + "&uge=" + currentWeek);
        }
Ejemplo n.º 9
0
        public DayInformationModel()
        {
            _year  = _myCal.GetYear(DateTime.Today);
            _month = _myCal.GetMonth(DateTime.Today);
            _day   = _myCal.GetDayOfMonth(DateTime.Today);

            _numDaysBeingDisplayed = 3;

            InitModel();
        }
Ejemplo n.º 10
0
 public static void GetLeapMonthTest(Calendar calendar, int yearHasLeapMonth, CalendarAlgorithmType algorithmType)
 {
     if (yearHasLeapMonth > 0)
     {
         Assert.NotEqual(calendar.GetLeapMonth(yearHasLeapMonth),  0);
         Assert.Equal(0, calendar.GetLeapMonth(yearHasLeapMonth - 1));
     }
     else
         Assert.True(calendar.GetLeapMonth(calendar.GetYear(DateTime.Today)) == 0, 
                     "calendar.GetLeapMonth returned wrong value");
 }
Ejemplo n.º 11
0
	public void FromDateTime(Calendar cal, DateTime time) {
		Date dmy = new Date();
		dmy.Day = cal.GetDayOfMonth(time);
		dmy.Month = cal.GetMonth(time);
		dmy.Year = cal.GetYear(time);
		dmy.Era = cal.GetEra(time);
		Day = dmy.Day;
		Month = dmy.Month;
		Year = dmy.Year;
		Era = dmy.Era;
	}
        internal void TimeToLunar(DateTime time, ref int year, ref int month, ref int day)
        {
            Calendar defaultInstance = GregorianCalendar.GetDefaultInstance();
            DateTime time1           = time;
            int      year1           = defaultInstance.GetYear(time1);
            DateTime time2           = time;
            int      month1          = defaultInstance.GetMonth(time2);
            DateTime time3           = time;
            int      dayOfMonth      = defaultInstance.GetDayOfMonth(time3);

            this.GregorianToLunar(year1, month1, dayOfMonth, ref year, ref month, ref day);
        }
        internal void TimeToLunar(DateTime time, ref int year, ref int month, ref int day)
        {
            int      nSYear          = 0;
            int      nSMonth         = 0;
            int      nSDate          = 0;
            Calendar defaultInstance = GregorianCalendar.GetDefaultInstance();

            nSYear  = defaultInstance.GetYear(time);
            nSMonth = defaultInstance.GetMonth(time);
            nSDate  = defaultInstance.GetDayOfMonth(time);
            this.GregorianToLunar(nSYear, nSMonth, nSDate, ref year, ref month, ref day);
        }
Ejemplo n.º 14
0
        internal void TimeToLunar(DateTime time, ref int year, ref int month, ref int day)
        {
            int gy = 0; int gm = 0; int gd = 0;

            Calendar Greg = GregorianCalendar.GetDefaultInstance();

            gy = Greg.GetYear(time);
            gm = Greg.GetMonth(time);
            gd = Greg.GetDayOfMonth(time);

            GregorianToLunar(gy, gm, gd, ref year, ref month, ref day);
        }
Ejemplo n.º 15
0
        private void PopulateYearComboBox()
        {
            DateTime today = DateTime.Now.Date;

            System.Globalization.Calendar thCalendar = thCulture.Calendar;
            int        currentYear        = thCalendar.GetYear(today);
            int        dataRetentionYears = int.Parse(ConfigurationManager.AppSettings["DataRetentionYears"].ToString());
            List <int> years = new List <int>();

            for (int i = currentYear; i >= currentYear - dataRetentionYears; i--)
            {
                years.Add(i);
            }
            cbbYear.ItemsSource  = years;
            cbbYear.SelectedItem = currentYear;
        }
Ejemplo n.º 16
0
 public virtual DateTime GetFromDate(DateTime dt, System.Globalization.Calendar calendar)
 {
     if (this.Order == 1 && this.FromMonth > this.ToMonth)
     {
         if (calendar.GetMonth(dt) == 1)
         {
             //در اولین بازه محدوده، ماه شروع در سال قبل قرار گرفته
             dt = calendar.AddYears(dt, -1);
         }
     }
     else if (this.Order == 0 && this.FromMonth >= this.ToMonth)
     {
         //بازه سالانه است و شروع در سال قبل قرار گرفته
         dt = calendar.AddYears(dt, -1);
     }
     return(calendar.ToDateTime(calendar.GetYear(dt), this.FromMonth, this.FromDay, 0, 0, 0, 0));
 }
Ejemplo n.º 17
0
      /// <summary>
      /// Initializes a new instance of the <see cref="MonthCalendarDate"/> class.
      /// </summary>
      /// <param name="cal">The calendar to use.</param>
      /// <param name="date">The gregorian date.</param>
      /// <exception cref="ArgumentNullException">If <paramref name="cal"/> is <c>null</c>.</exception>
      public MonthCalendarDate(Calendar cal, DateTime date)
      {
         if (cal == null)
         {
            throw new ArgumentNullException("cal", "parameter 'cal' cannot be null.");
         }

         if (date < cal.MinSupportedDateTime)
         {
            date = cal.MinSupportedDateTime;
         }

         if (date > cal.MaxSupportedDateTime)
         {
            date = cal.MaxSupportedDateTime;
         }

         this.Year = cal.GetYear(date);
         this.Month = cal.GetMonth(date);
         this.Day = cal.GetDayOfMonth(date);
         this.Era = cal.GetEra(date);
         this.calendar = cal;
      }
Ejemplo n.º 18
0
        // ----------------------------------------------------------------------
        // 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 );
        }
Ejemplo n.º 19
0
 private string GetDateInPersianCalendar(DateTime dateTime)
 {
     return($"{PersianCalendar.GetYear(dateTime):0000}/{PersianCalendar.GetMonth(dateTime):00}/{PersianCalendar.GetDayOfMonth(dateTime):00}");
 }
Ejemplo n.º 20
0
        private static void CheckDefaultDateTime(ref DateTimeResult result, ref Calendar cal, DateTimeStyles styles) {

            if ((result.Year == -1) || (result.Month == -1) || (result.Day == -1)) {
                /*
                The following table describes the behaviors of getting the default value
                when a certain year/month/day values are missing.

                An "X" means that the value exists.  And "--" means that value is missing.

                Year    Month   Day =>  ResultYear  ResultMonth     ResultDay       Note

                X       X       X       Parsed year Parsed month    Parsed day
                X       X       --      Parsed Year Parsed month    First day       If we have year and month, assume the first day of that month.
                X       --      X       Parsed year First month     Parsed day      If the month is missing, assume first month of that year.
                X       --      --      Parsed year First month     First day       If we have only the year, assume the first day of that year.

                --      X       X       CurrentYear Parsed month    Parsed day      If the year is missing, assume the current year.
                --      X       --      CurrentYear Parsed month    First day       If we have only a month value, assume the current year and current day.
                --      --      X       CurrentYear First month     Parsed day      If we have only a day value, assume current year and first month.
                --      --      --      CurrentYear Current month   Current day     So this means that if the date string only contains time, you will get current date.

                */

                DateTime now = DateTime.Now;
                if (result.Month == -1 && result.Day == -1) {
                    if (result.Year == -1) {
                        if ((styles & DateTimeStyles.NoCurrentDateDefault) != 0) {
                            // If there is no year/month/day values, and NoCurrentDateDefault flag is used,
                            // set the year/month/day value to the beginning year/month/day of DateTime().
                            // Note we should be using Gregorian for the year/month/day.
                            cal = GregorianCalendar.GetDefaultInstance();
                            result.Year = result.Month = result.Day = 1;
                        } else {
                            // Year/Month/Day are all missing.
                            result.Year = cal.GetYear(now);
                            result.Month = cal.GetMonth(now);
                            result.Day = cal.GetDayOfMonth(now);
                        }
                    } else {
                        // Month/Day are both missing.
                        result.Month = 1;
                        result.Day = 1;
                    }
                } else {
                    if (result.Year == -1) {
                        result.Year = cal.GetYear(now);
                    }
                    if (result.Month == -1) {
                        result.Month = 1;
                    }
                    if (result.Day == -1) {
                        result.Day = 1;
                    }
                }
            }
            // Set Hour/Minute/Second to zero if these value are not in str.
            if (result.Hour   == -1) result.Hour = 0;
            if (result.Minute == -1) result.Minute = 0;
            if (result.Second == -1) result.Second = 0;
            if (result.era == -1) result.era = Calendar.CurrentEra;
        }
Ejemplo n.º 21
0
        /// <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);
        }
Ejemplo n.º 22
0
        // This is copied from the generic implementation of GetWeekOfYearFullDays() in Calendar.cs.  The generic implementation is not good enough
        // in the case of FristFullWeek and FirstFourDayWeek since it needs the data for B.C. year 1 near 0001/1/1.
        // We override the generic implementation to handle this special case.

        // Parameters
        //
        internal static int InternalGetWeekOfYearFullDays(Calendar cal, DateTime time, int firstDayOfWeek, int fullDays, int daysOfMinYearMinusOne)
        {
            int dayForJan1;
            int offset;
            int day;

            int dayOfYear = cal.GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.

            //
            // Calculate the number of days between the first day of year (1/1) and the first day of the week.
            // This value will be a positive value from 0 ~ 6.  We call this value as "offset".
            //
            // If offset is 0, it means that the 1/1 is the start of the first week.
            //     Assume the first day of the week is Monday, it will look like this:
            //     Sun      Mon     Tue     Wed     Thu     Fri     Sat
            //     12/31    1/1     1/2     1/3     1/4     1/5     1/6
            //              +--> First week starts here.
            //
            // If offset is 1, it means that the first day of the week is 1 day ahead of 1/1.
            //     Assume the first day of the week is Monday, it will look like this:
            //     Sun      Mon     Tue     Wed     Thu     Fri     Sat
            //     1/1      1/2     1/3     1/4     1/5     1/6     1/7
            //              +--> First week starts here.
            //
            // If offset is 2, it means that the first day of the week is 2 days ahead of 1/1.
            //     Assume the first day of the week is Monday, it will look like this:
            //     Sat      Sun     Mon     Tue     Wed     Thu     Fri     Sat
            //     1/1      1/2     1/3     1/4     1/5     1/6     1/7     1/8
            //                      +--> First week starts here.



            // Day of week is 0-based.
            // Get the day of week for 1/1.  This can be derived from the day of week of the target day.
            // Note that we can get a negative value.  It's ok since we are going to make it a positive value when calculating the offset.
            dayForJan1 = (int)cal.GetDayOfWeek(time) - (dayOfYear % 7);

            // Now, calucalte the offset.  Substract the first day of week from the dayForJan1.  And make it a positive value.
            offset = (firstDayOfWeek - dayForJan1 + 14) % 7;
            if (offset != 0 && offset >= fullDays)
            {
                //
                // If the offset is greater than the value of fullDays, it means that
                // the first week of the year starts on the week where Jan/1 falls on.
                //
                offset -= 7;
            }
            //
            // Calculate the day of year for specified time by taking offset into account.
            //
            day = dayOfYear - offset;
            if (day >= 0)
            {
                //
                // If the day of year value is greater than zero, get the week of year.
                //
                return(day / 7 + 1);
            }
            //
            // Otherwise, the specified time falls on the week of previous year.
            // Note that it is not always week 52 or 53, because it depends on the calendar.  Different calendars have different number of days in a year.
            //

            // Repeat the previous calculation logic using the previous year and calculate the week of year for the last day of previous year.
            int year = cal.GetYear(time);

            if (year <= cal.GetYear(cal.MinSupportedDateTime))
            {
                // This specified time is in 0001/1/1 ~ 0001/1/7.
                dayOfYear = daysOfMinYearMinusOne;
            }
            else
            {
                dayOfYear = cal.GetDaysInYear(year - 1);
            }
            dayForJan1 = dayForJan1 - (dayOfYear % 7);
            // Now, calucalte the offset.  Substract the first day of week from the dayForJan1.  And make it a positive value.
            offset = (firstDayOfWeek - dayForJan1 + 14) % 7;
            if (offset != 0 && offset >= fullDays)
            {
                //
                // If the offset is greater than the value of fullDays, it means that
                // the first week of the year starts on the week where Jan/1 falls on.
                //
                offset -= 7;
            }
            //
            // Calculate the day of year for specified time by taking offset into account.
            //
            day = dayOfYear - offset;
            return(day / 7 + 1);
        }
		private static bool CheckDefaultDateTime(ref DateTimeResult result, ref Calendar cal, DateTimeStyles styles)
		{
			if ((result.flags & ParseFlags.CaptureOffset) != (ParseFlags)0 && (result.Month != -1 || result.Day != -1) && (result.Year == -1 || (result.flags & ParseFlags.YearDefault) != (ParseFlags)0) && (result.flags & ParseFlags.TimeZoneUsed) != (ParseFlags)0)
			{
				result.SetFailure(ParseFailureKind.Format, "Format_MissingIncompleteDate", null);
				return false;
			}
			if (result.Year == -1 || result.Month == -1 || result.Day == -1)
			{
				DateTime dateTimeNow = DateTimeParse.GetDateTimeNow(ref result, ref styles);
				if (result.Month == -1 && result.Day == -1)
				{
					if (result.Year == -1)
					{
						if ((styles & DateTimeStyles.NoCurrentDateDefault) != DateTimeStyles.None)
						{
							cal = GregorianCalendar.GetDefaultInstance();
							result.Year = (result.Month = (result.Day = 1));
						}
						else
						{
							result.Year = cal.GetYear(dateTimeNow);
							result.Month = cal.GetMonth(dateTimeNow);
							result.Day = cal.GetDayOfMonth(dateTimeNow);
						}
					}
					else
					{
						result.Month = 1;
						result.Day = 1;
					}
				}
				else
				{
					if (result.Year == -1)
					{
						result.Year = cal.GetYear(dateTimeNow);
					}
					if (result.Month == -1)
					{
						result.Month = 1;
					}
					if (result.Day == -1)
					{
						result.Day = 1;
					}
				}
			}
			if (result.Hour == -1)
			{
				result.Hour = 0;
			}
			if (result.Minute == -1)
			{
				result.Minute = 0;
			}
			if (result.Second == -1)
			{
				result.Second = 0;
			}
			if (result.era == -1)
			{
				result.era = 0;
			}
			return true;
		}
Ejemplo n.º 24
0
        //---- Aplica configuraciones
        private void button_ConfAplicar_Click(object sender, RoutedEventArgs e)
        {
            if (textBox_NombreUsuario.Text.Length < 1 && textBox_NombreUsuario.Text.Length < 1)
            {
                return;
            }

            nombre_Usuario      = textBox_NombreUsuario.Text;
            nombre_Gerente      = textBox_NombreGerente.Text;
            notificaciones_modo = comboBox_Notificaciones.SelectedIndex;
            recordatorio_activo = (bool)checkBox_Recordatorio.IsChecked;
            email_To            = textBox_EmailTo.Text;
            email_Cc            = textBox_EmailCc.Text;

            scroll_Actividades.Visibility   = Visibility.Visible;
            scroll_Configuracion.Visibility = button_ConfAplicar.Visibility = Visibility.Collapsed;

            //--------------------------------------------------------- Fecha de TOP
            DateTime           temp = DateTime.Now;
            DateTimeFormatInfo dfi  = DateTimeFormatInfo.CurrentInfo;

            System.Globalization.Calendar cal = dfi.Calendar;
            label_Semana.Content = "Semana " + cal.GetWeekOfYear(temp, dfi.CalendarWeekRule, dfi.FirstDayOfWeek) + ", " + cal.GetYear(temp) + " " + getNameInitials(nombre_Usuario);

            //---- Inicia los timers
            timersSettup();

            savePreferences();
        }
Ejemplo n.º 25
0
        //----------------------------------------------------------------------------------------------

        //---- Constructor
        public MainWindow()
        {
            InitializeComponent();

            //-------------------------------------------------------- Carga configuraciones
            loadPreferences();

            //--------------------------------------------------------- Lista de actividades
            listaActividades = loadSavedActivities();
            if (listaActividades != null && listaActividades.Count > 0)
            {
                displaySavedActivities();
            }
            else
            {
                listaActividades = new List <ActividadesSheet>();
            }

            //--------------------------------------------------------- Fecha de TOP
            DateTime           temp = DateTime.Now;
            DateTimeFormatInfo dfi  = DateTimeFormatInfo.CurrentInfo;

            System.Globalization.Calendar cal = dfi.Calendar;
            label_Semana.Content = "Semana " + cal.GetWeekOfYear(temp, dfi.CalendarWeekRule, dfi.FirstDayOfWeek) + ", " + cal.GetYear(temp) + " " + getNameInitials(nombre_Usuario);

            //-------------------------------------------------------- Inicializa timer
            timersSettup();
        }
Ejemplo n.º 26
0
 private Boolean ResultCorrect(DateTime returned, DateTime expected, String format, CultureInfo culture, Calendar cal)
   {
   switch(format)
     {
     case "m":
     case "M":
       if(cal is HijriCalendar)
	 {
	 if(cal.GetYear(DateTime.Now) != cal.GetYear(returned))
	   return false;
	 return (returned.ToString("m", culture)==expected.ToString("m", culture));
	 }
       else
	 return ((returned.Month==expected.Month) && (returned.Day==expected.Day));
     case "t":
       return ((returned.Hour==expected.Hour) && (returned.Minute==expected.Minute));
     case "T":
       return ((returned.Hour==expected.Hour) && (returned.Minute==expected.Minute) && (returned.Second==expected.Second));
     case "u":
       return (returned==expected);				
     case "y":
     case "Y":
       if(cal is HijriCalendar)
	 {
	 return (returned.ToString("y", culture.DateTimeFormat)==expected.ToString("y", culture.DateTimeFormat));
	 }
       else
	 return ((returned.Month==expected.Month) && (returned.Year==expected.Year));
     default:
       return (returned==expected);
     }
   }
Ejemplo n.º 27
0
        public static DateTime?SetYear(DateTime date, DateTime yearDate)
        {
            int curYear = cal.GetYear(date);
            int newYear = cal.GetYear(yearDate);

            return(DateTimeHelper.AddYears(date, newYear - curYear));
        }
Ejemplo n.º 28
0
        public static int Year( this DateTime date, Calendar calendar )
        {
            Arg.NotNull( calendar, nameof( calendar ) );
            Contract.Ensures( Contract.Result<int>() > 0 );
            Contract.Ensures( Contract.Result<int>() < 10000 );

            return calendar.GetYear( date );
        }
Ejemplo n.º 29
0
        internal CalendarButton GetCalendarButton(DateTime date, CalendarMode mode)
        {
            Debug.Assert(mode != CalendarMode.Month);

            foreach (CalendarButton b in GetCalendarButtons())
            {
                if (b != null && b.DataContext is DateTime)
                {
                    if (mode == CalendarMode.Year)
                    {
                        if (DateTimeHelper.CompareYearMonth(date, (DateTime)b.DataContext) == 0)
                        {
                            return(b);
                        }
                    }
                    else
                    {
                        if (_calendar.GetYear(date) == _calendar.GetYear(((DateTime)b.DataContext)))
                        {
                            return(b);
                        }
                    }
                }
            }

            return(null);
        }
Ejemplo n.º 30
0
        public void UpdateMonthMode()
        {
            Debug.Assert(this._owner.DisplayDate != null);
            _currentMonth = (DateTime)this._owner.DisplayDate;


            _firstDayOfWeek = this._owner.FirstDayOfWeek;

            if (_currentMonth != null)
            {
                int      year            = _calendar.GetYear(_currentMonth);
                int      month           = _calendar.GetMonth(_currentMonth);
                DateTime firstDayOfMonth = new DateTime(year, month, 1);

                if (this._headerButton != null)
                {
                    this._headerButton.Content = string.Format(CultureInfo.CurrentCulture, Resource.Calendar_MonthViewHeaderText,
                                                               CultureInfo.CurrentCulture.DateTimeFormat.MonthNames[month - 1],
                                                               year.ToString(CultureInfo.CurrentCulture));

                    this._headerButton.IsEnabled = true;
                }

                int      lastMonthToDisplay  = PreviousMonthDays(firstDayOfMonth);
                DateTime dateToAdd           = _calendar.AddDays(firstDayOfMonth, -lastMonthToDisplay);
                DateTime firstDayOfNextMonth = _calendar.AddMonths(firstDayOfMonth, 1);

                // check to see if Prev/Next Buttons will be displayed
                if (_previousButton != null)
                {
                    if (DateTime.Compare(_owner.DisplayDateStart.GetValueOrDefault(DateTime.MinValue), firstDayOfMonth) > -1)
                    {
                        _previousButton.IsEnabled = false;
                    }
                    else
                    {
                        _previousButton.IsEnabled = true;
                    }
                }

                if (_nextButton != null)
                {
                    if (DateTime.Compare(_owner.DisplayDateEnd.GetValueOrDefault(DateTime.MaxValue), firstDayOfNextMonth) < 0)
                    {
                        _nextButton.IsEnabled = false;
                    }
                    else
                    {
                        _nextButton.IsEnabled = true;
                    }
                }

                int count = 0;

                if (_monthGrid != null)
                {
                    Debug.Assert(_monthGrid.Children.Count == COLS * ROWS);
                    //Set the day titles
                    foreach (object child in _monthGrid.Children)
                    {
                        if (count < (COLS))
                        {
                            //this assumes that the day titles are always text blocks
                            TextBlock daytitle = child as TextBlock;
                            Debug.Assert(daytitle != null);
                            daytitle.Text = CultureInfo.CurrentCulture.DateTimeFormat.AbbreviatedDayNames[(count + (int)_firstDayOfWeek) % NUMBER_OF_DAYS_IN_WEEK];
                        }
                        else
                        {
                            DayButton mybutton = child as DayButton;
                            Debug.Assert(mybutton != null);

                            SetButtonState(mybutton, dateToAdd);

                            mybutton.IsTabStop = false;

                            if (_currentButton == null)
                            {
                                if (_owner.SelectedDate == null && mybutton.IsToday)
                                {
                                    mybutton.IsTabStop = true;
                                    _currentButton     = mybutton;
                                    mybutton.IsCurrent = true;
                                }
                                else
                                {
                                    if (mybutton.IsSelected)
                                    {
                                        mybutton.IsTabStop = true;
                                        _currentButton     = mybutton;
                                        mybutton.IsCurrent = true;
                                    }
                                }
                            }

                            mybutton.Content     = String.Format(CultureInfo.CurrentCulture, "{0,2}", dateToAdd.Day);
                            mybutton.DataContext = dateToAdd;
                            dateToAdd            = _calendar.AddDays(dateToAdd, 1);
                        }
                        count++;
                    }
                }
            }
        }
        /// <summary>
        /// DateDiff in SQL style.
        /// Date-part implemented:
        /// "year" (abbr. "yy", "yyyy"),
        /// "quarter" (abbr. "qq", "q"),
        /// "month" (abbr. "mm", "m"),
        /// "day" (abbr. "dd", "d"),
        /// "week" (abbr. "wk", "ww"),
        /// "hour" (abbr. "hh"),
        /// "minute" (abbr. "mi", "n"),
        /// "second" (abbr. "ss", "s"),
        /// "millisecond" (abbr. "ms").
        /// </summary>
        /// <param name="startDate">The start date.</param>
        /// <param name="endDate">The end date.</param>
        /// <param name="datePart">The date part.</param>
        /// <returns>Date Difference in System.long</returns>
        /// <exception cref="Exception"></exception>
        public static long DateDiff(this DateTime startDate, DateTime endDate, string datePart)
        {
            long DateDiffVal = 0;

            System.Globalization.Calendar cal = System.Threading.Thread.CurrentThread.CurrentCulture.Calendar;
            TimeSpan ts = new TimeSpan(endDate.Ticks - startDate.Ticks);

            switch (datePart.ToLower().Trim())
            {
                #region year
            case "year":
            case "yy":
            case "yyyy":
                DateDiffVal = (long)(cal.GetYear(endDate) - cal.GetYear(startDate));
                break;
                #endregion

                #region quarter
            case "quarter":
            case "qq":
            case "q":
                DateDiffVal = (long)((((cal.GetYear(endDate)
                                        - cal.GetYear(startDate)) * 4)
                                      + ((cal.GetMonth(endDate) - 1) / 3))
                                     - ((cal.GetMonth(startDate) - 1) / 3));
                break;
                #endregion

                #region month
            case "month":
            case "mm":
            case "m":
                DateDiffVal = (long)(((cal.GetYear(endDate)
                                       - cal.GetYear(startDate)) * 12
                                      + cal.GetMonth(endDate))
                                     - cal.GetMonth(startDate));
                break;
                #endregion

                #region day
            case "day":
            case "d":
            case "dd":
                DateDiffVal = (long)ts.TotalDays;
                break;
                #endregion

                #region week
            case "week":
            case "wk":
            case "ww":
                DateDiffVal = (long)(ts.TotalDays / 7);
                break;
                #endregion

                #region hour
            case "hour":
            case "hh":
                DateDiffVal = (long)ts.TotalHours;
                break;
                #endregion

                #region minute
            case "minute":
            case "mi":
            case "n":
                DateDiffVal = (long)ts.TotalMinutes;
                break;
                #endregion

                #region second
            case "second":
            case "ss":
            case "s":
                DateDiffVal = (long)ts.TotalSeconds;
                break;
                #endregion

                #region millisecond
            case "millisecond":
            case "ms":
                DateDiffVal = (long)ts.TotalMilliseconds;
                break;
                #endregion

            default:
                throw new Exception(string.Format("DatePart \"{0}\" is unknown", datePart));
            }
            return(DateDiffVal);
        }
Ejemplo n.º 32
0
 internal static int InternalGetWeekOfYearFullDays(Calendar cal, DateTime time, int firstDayOfWeek, int fullDays, int daysOfMinYearMinusOne)
 {
     int daysInYear = cal.GetDayOfYear(time) - 1;
     int num = ((int) cal.GetDayOfWeek(time)) - (daysInYear % 7);
     int num2 = ((firstDayOfWeek - num) + 14) % 7;
     if ((num2 != 0) && (num2 >= fullDays))
     {
         num2 -= 7;
     }
     int num3 = daysInYear - num2;
     if (num3 < 0)
     {
         int year = cal.GetYear(time);
         if (year <= cal.GetYear(cal.MinSupportedDateTime))
         {
             daysInYear = daysOfMinYearMinusOne;
         }
         else
         {
             daysInYear = cal.GetDaysInYear(year - 1);
         }
         num -= daysInYear % 7;
         num2 = ((firstDayOfWeek - num) + 14) % 7;
         if ((num2 != 0) && (num2 >= fullDays))
         {
             num2 -= 7;
         }
         num3 = daysInYear - num2;
     }
     return ((num3 / 7) + 1);
 }
Ejemplo n.º 33
0
        public static DateTime StartOfMonth( this DateTime date, Calendar calendar )
        {
            Arg.NotNull( calendar, nameof( calendar ) );
            Contract.Ensures( calendar.GetYear( Contract.Result<DateTime>() ) == Contract.OldValue( calendar.GetYear( date ) ) );
            Contract.Ensures( calendar.GetMonth( Contract.Result<DateTime>() ) == Contract.OldValue( calendar.GetMonth( date ) ) );

            var year = calendar.GetYear( date );
            var month = calendar.GetMonth( date );
            return calendar.ToDateTime( year, month, 1, date.Hour, date.Minute, date.Second, date.Millisecond );
        }
Ejemplo n.º 34
0
        // This is copied from the generic implementation of GetWeekOfYearFullDays() in Calendar.cs.  The generic implementation is not good enough 
        // in the case of FristFullWeek and FirstFourDayWeek since it needs the data for B.C. year 1 near 0001/1/1.
        // We override the generic implementation to handle this special case.

        // Parameters 
        //
        internal static int InternalGetWeekOfYearFullDays(Calendar cal, DateTime time, int firstDayOfWeek, int fullDays, int daysOfMinYearMinusOne) { 
            int dayForJan1; 
            int offset;
            int day; 

            int dayOfYear = cal.GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
            //
            // Calculate the number of days between the first day of year (1/1) and the first day of the week. 
            // This value will be a positive value from 0 ~ 6.  We call this value as "offset".
            // 
            // If offset is 0, it means that the 1/1 is the start of the first week. 
            //     Assume the first day of the week is Monday, it will look like this:
            //     Sun      Mon     Tue     Wed     Thu     Fri     Sat 
            //     12/31    1/1     1/2     1/3     1/4     1/5     1/6
            //              +--> First week starts here.
            //
            // If offset is 1, it means that the first day of the week is 1 day ahead of 1/1. 
            //     Assume the first day of the week is Monday, it will look like this:
            //     Sun      Mon     Tue     Wed     Thu     Fri     Sat 
            //     1/1      1/2     1/3     1/4     1/5     1/6     1/7 
            //              +--> First week starts here.
            // 
            // If offset is 2, it means that the first day of the week is 2 days ahead of 1/1.
            //     Assume the first day of the week is Monday, it will look like this:
            //     Sat      Sun     Mon     Tue     Wed     Thu     Fri     Sat
            //     1/1      1/2     1/3     1/4     1/5     1/6     1/7     1/8 
            //                      +--> First week starts here.
 
 

            // Day of week is 0-based. 
            // Get the day of week for 1/1.  This can be derived from the day of week of the target day.
            // Note that we can get a negative value.  It's ok since we are going to make it a positive value when calculating the offset.
            dayForJan1 = (int)cal.GetDayOfWeek(time) - (dayOfYear % 7);
 
            // Now, calucalte the offset.  Substract the first day of week from the dayForJan1.  And make it a positive value.
            offset = (firstDayOfWeek - dayForJan1 + 14) % 7; 
            if (offset != 0 && offset >= fullDays) 
            {
                // 
                // If the offset is greater than the value of fullDays, it means that
                // the first week of the year starts on the week where Jan/1 falls on.
                //
                offset -= 7; 
            }
            // 
            // Calculate the day of year for specified time by taking offset into account. 
            //
            day = dayOfYear - offset; 
            if (day >= 0) {
                //
                // If the day of year value is greater than zero, get the week of year.
                // 
                return (day/7 + 1);
            } 
            // 
            // Otherwise, the specified time falls on the week of previous year.
            // Note that it is not always week 52 or 53, because it depends on the calendar.  Different calendars have different number of days in a year. 
            //

            // Repeat the previous calculation logic using the previous year and calculate the week of year for the last day of previous year.
            int year = cal.GetYear(time); 
            if (year <= cal.GetYear(cal.MinSupportedDateTime)) {
                // This specified time is in 0001/1/1 ~ 0001/1/7. 
                dayOfYear = daysOfMinYearMinusOne; 
            } else {
                dayOfYear = cal.GetDaysInYear(year - 1); 
            }
            dayForJan1 = dayForJan1 - (dayOfYear % 7);
            // Now, calucalte the offset.  Substract the first day of week from the dayForJan1.  And make it a positive value.
            offset = (firstDayOfWeek - dayForJan1 + 14) % 7; 
            if (offset != 0 && offset >= fullDays)
            { 
                // 
                // If the offset is greater than the value of fullDays, it means that
                // the first week of the year starts on the week where Jan/1 falls on. 
                //
                offset -= 7;
            }
            // 
            // Calculate the day of year for specified time by taking offset into account.
            // 
            day = dayOfYear - offset; 
            return (day/7 + 1);
        } 
Ejemplo n.º 35
0
 private void VerifyAddMonthsResult(Calendar calendar, DateTime oldTime, DateTime newTime, int months)
 {
     int oldYear = calendar.GetYear(oldTime);
     int oldMonth = calendar.GetMonth(oldTime);
     int oldDay = calendar.GetDayOfMonth(oldTime);
     long oldTicksOfDay = oldTime.Ticks % TimeSpan.TicksPerDay;
     int newYear = calendar.GetYear(newTime);
     int newMonth = calendar.GetMonth(newTime);
     int newDay = calendar.GetDayOfMonth(newTime);
     long newTicksOfDay = newTime.Ticks % TimeSpan.TicksPerDay;
     Assert.Equal(oldTicksOfDay, newTicksOfDay);
     Assert.False(newDay > oldDay);
     Assert.False(newYear * 12 + newMonth != oldYear * 12 + oldMonth + months);
 }
Ejemplo n.º 36
0
        public static DateTime StartOfSemester( this DateTime date, Calendar calendar )
        {
            Arg.NotNull( calendar, nameof( calendar ) );
            Contract.Ensures( calendar.GetYear( Contract.Result<DateTime>() ) == Contract.OldValue( calendar.GetYear( date ) ) );
            Contract.Ensures( Contract.Result<DateTime>().Semester( calendar ) == Contract.OldValue( date.Semester( calendar ) ) );

            var semester = date.Semester( calendar );
            return calendar.AddMonths( date.StartOfYear( calendar ), ( semester - 1 ) * 6 );
        }
Ejemplo n.º 37
0
        private static bool CheckDefaultDateTime(ref DateTimeResult result, ref Calendar cal, DateTimeStyles styles) {

            if ((result.flags & ParseFlags.CaptureOffset) != 0) {
                // DateTimeOffset.Parse should allow dates without a year, but only if there is also no time zone marker;
                // e.g. "May 1 5pm" is OK, but "May 1 5pm -08:30" is not.  This is somewhat pragmatic, since we would
                // have to rearchitect parsing completely to allow this one case to correctly handle things like leap
                // years and leap months.  Is is an extremely corner case, and DateTime is basically incorrect in that
                // case today.
                //
                // values like "11:00Z" or "11:00 -3:00" are also acceptable
                //
                // if ((month or day is set) and (year is not set and time zone is set))
                //
                if (  ((result.Month != -1) || (result.Day != -1)) 
                    && ((result.Year == -1 || ((result.flags & ParseFlags.YearDefault) != 0)) && (result.flags & ParseFlags.TimeZoneUsed) != 0) ) {
                    result.SetFailure(ParseFailureKind.Format, "Format_MissingIncompleteDate", null);
                    return false;
                }
            }


            if ((result.Year == -1) || (result.Month == -1) || (result.Day == -1)) {
                /*
                The following table describes the behaviors of getting the default value
                when a certain year/month/day values are missing.

                An "X" means that the value exists.  And "--" means that value is missing.

                Year    Month   Day =>  ResultYear  ResultMonth     ResultDay       Note

                X       X       X       Parsed year Parsed month    Parsed day
                X       X       --      Parsed Year Parsed month    First day       If we have year and month, assume the first day of that month.
                X       --      X       Parsed year First month     Parsed day      If the month is missing, assume first month of that year.
                X       --      --      Parsed year First month     First day       If we have only the year, assume the first day of that year.

                --      X       X       CurrentYear Parsed month    Parsed day      If the year is missing, assume the current year.
                --      X       --      CurrentYear Parsed month    First day       If we have only a month value, assume the current year and current day.
                --      --      X       CurrentYear First month     Parsed day      If we have only a day value, assume current year and first month.
                --      --      --      CurrentYear Current month   Current day     So this means that if the date string only contains time, you will get current date.

                */
                
                DateTime now = GetDateTimeNow(ref result, ref styles);
                if (result.Month == -1 && result.Day == -1) {
                    if (result.Year == -1) {
                        if ((styles & DateTimeStyles.NoCurrentDateDefault) != 0) {
                            // If there is no year/month/day values, and NoCurrentDateDefault flag is used,
                            // set the year/month/day value to the beginning year/month/day of DateTime().
                            // Note we should be using Gregorian for the year/month/day.
                            cal = GregorianCalendar.GetDefaultInstance();
                            result.Year = result.Month = result.Day = 1;
                        } else {
                            // Year/Month/Day are all missing.
                            result.Year = cal.GetYear(now);
                            result.Month = cal.GetMonth(now);
                            result.Day = cal.GetDayOfMonth(now);
                        }
                    } else {
                        // Month/Day are both missing.
                        result.Month = 1;
                        result.Day = 1;
                    }
                } else {
                    if (result.Year == -1) {
                        result.Year = cal.GetYear(now);
                    }
                    if (result.Month == -1) {
                        result.Month = 1;
                    }
                    if (result.Day == -1) {
                        result.Day = 1;
                    }
                }
            }
            // Set Hour/Minute/Second to zero if these value are not in str.
            if (result.Hour   == -1) result.Hour = 0;
            if (result.Minute == -1) result.Minute = 0;
            if (result.Second == -1) result.Second = 0;
            if (result.era == -1) result.era = Calendar.CurrentEra;
            return true;
        }
Ejemplo n.º 38
0
        public static DateTime StartOfYear( this DateTime date, Calendar calendar )
        {
            Arg.NotNull( calendar, nameof( calendar ) );
            Contract.Ensures( calendar.GetYear( Contract.Result<DateTime>() ) == Contract.OldValue( calendar.GetYear( date ) ) );

            return date.AddDays( (double) ( -calendar.GetDayOfYear( date ) + 1 ) );
        }
Ejemplo n.º 39
0
      /// <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;
      }
Ejemplo n.º 40
0
        public static DateTime EndOfYear( this DateTime date, Calendar calendar )
        {
            Arg.NotNull( calendar, nameof( calendar ) );
            Contract.Ensures( calendar.GetYear( Contract.Result<DateTime>() ) == Contract.OldValue( calendar.GetYear( date ) ) );

            return calendar.AddYears( date.StartOfYear( calendar ), 1 ).AddTicks( -1L );
        }