/// <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);
                    }
                }
            }
        }
 // Use this for initialization
 void Start()
 {
     currencySys = GetComponent<CurrencySystem>();
     clockSys = GetComponent<ClockSystem>();
     updateSys = GetComponent<UpdateSytem>();
     calendarSys = GetComponent<CalendarSystem>();
 }
 private int GetDaysInFirstWeek(int year, CalendarSystem calendar)
 {
     // Some of the first few days of the week year may be in the previous week year.
     // However, the whole of the first week of the week year definitely occurs
     // within the first 13 days of January.
     return Enumerable.Range(1, 13)
                      .Count(day => new LocalDate(year, 1, day, calendar).WeekOfWeekYear == 1);
 }
        private static void ValidateProperties(CalendarSystem calendar, int daysSinceEpoch, int expectedYear)
        {
            var localDate = new LocalDate(daysSinceEpoch, calendar);
            Assert.AreEqual(expectedYear, localDate.Year);

            foreach (var property in typeof(LocalDate).GetTypeInfo().DeclaredProperties)
            {
                property.GetValue(localDate, null);
            }
        }
        /// <summary>
        /// Converts each day in a full leap cycle (for coverage of different scenarios) to the ISO
        /// calendar and back. This exercises fetching the number of days since the epoch and getting
        /// a year/month/day *from* a number of days.
        /// </summary>
        private static void TestLeapCycle(CalendarSystem calendar)
        {
            for (int year = 5400; year < 5419; year++)
            {
#if !V1
                int maxMonth = calendar.GetMonthsInYear(year);
#else
                int maxMonth = calendar.GetMaxMonth(year);
#endif
                for (int month = 1; month <= maxMonth; month++)
                {
                    int maxDay = calendar.GetDaysInMonth(year, month);
                    for (int day = 1; day <= maxDay; day++)
                    {
                        var date = new LocalDate(year, month, day, calendar);
                        date.WithCalendar(CalendarSystem.Iso).WithCalendar(calendar).Consume();
                    }
                }
            }
        }
Example #6
0
        public void BetweenLocalDateTimes_OnLeapYearIslamic()
        {
            var calendar = CalendarSystem.GetIslamicCalendar(IslamicLeapYearPattern.Base15, IslamicEpoch.Civil);

            Assert.IsTrue(calendar.IsLeapYear(2));
            Assert.IsFalse(calendar.IsLeapYear(3));

            LocalDateTime dt1 = new LocalDateTime(2, 12, 30, 2, 0, calendar);
            LocalDateTime dt2 = new LocalDateTime(2, 12, 30, 4, 0, calendar);
            LocalDateTime dt3 = new LocalDateTime(3, 12, 29, 3, 0, calendar);

            // Adding a year truncates to 0003-12-28T02:00:00, then add an hour.
            Assert.AreEqual(Parse("P1YT1H"), Period.Between(dt1, dt3));
            // Adding a year would overshoot. Adding 11 months takes us to month 03-11-30T04:00.
            // Adding another 28 days takes us to 03-12-28T04:00, then add another 23 hours to finish.
            Assert.AreEqual(Parse("P11M28DT23H"), Period.Between(dt2, dt3));

            // Subtracting 11 months takes us to 03-01-29T03:00. Subtracting another 29 days
            // takes us to 02-12-30T03:00, and another hour to get to the target.
            Assert.AreEqual(Parse("P-11M-29DT-1H"), Period.Between(dt3, dt1));
            Assert.AreEqual(Parse("P-11M-28DT-23H"), Period.Between(dt3, dt2));
        }
Example #7
0
        public void LocalComparer()
        {
            var localControl      = new LocalDateTime(2013, 4, 2, 19, 54);
            var control           = new OffsetDateTime(localControl, Offset.Zero);
            var negativeOffset    = control.LocalDateTime.WithOffset(Offset.FromHours(-1));
            var positiveOffset    = control.LocalDateTime.WithOffset(Offset.FromHours(1));
            var differentCalendar = control.LocalDateTime.WithCalendar(CalendarSystem.GetCopticCalendar(4)).WithOffset(Offset.FromHours(5));
            // Later instant, earlier local
            var earlierLocal = control.LocalDateTime.PlusHours(-2).WithOffset(Offset.FromHours(-10));
            // Earlier instant, later local
            var laterLocal = control.LocalDateTime.PlusHours(2).WithOffset(Offset.FromHours(10));

            var comparer = OffsetDateTime.Comparer.Local;

            Assert.AreEqual(0, comparer.Compare(control, negativeOffset));
            Assert.AreEqual(0, comparer.Compare(control, positiveOffset));
            Assert.AreEqual(0, comparer.Compare(control, differentCalendar));
            Assert.AreEqual(1, Math.Sign(comparer.Compare(control, earlierLocal)));
            Assert.AreEqual(-1, Math.Sign(comparer.Compare(earlierLocal, control)));
            Assert.AreEqual(-1, Math.Sign(comparer.Compare(control, laterLocal)));
            Assert.AreEqual(1, Math.Sign(comparer.Compare(laterLocal, control)));
        }
        /// <summary>
        /// Converts each day in a full leap cycle (for coverage of different scenarios) to the ISO
        /// calendar and back. This exercises fetching the number of days since the epoch and getting
        /// a year/month/day *from* a number of days.
        /// </summary>
        private static LocalDate TestLeapCycle(CalendarSystem calendar)
        {
            LocalDate returnLocalDate = new LocalDate();

            for (int year = 5400; year < 5419; year++)
            {
#if !V1
                int maxMonth = calendar.GetMonthsInYear(year);
#else
                int maxMonth = calendar.GetMaxMonth(year);
#endif
                for (int month = 1; month <= maxMonth; month++)
                {
                    int maxDay = calendar.GetDaysInMonth(year, month);
                    for (int day = 1; day <= maxDay; day++)
                    {
                        var date = new LocalDate(year, month, day, calendar);
                        returnLocalDate = date.WithCalendar(CalendarSystem.Iso).WithCalendar(calendar);
                    }
                }
            }
            return(returnLocalDate);
        }
Example #9
0
        /// <summary>
        /// Creates a character handler for the calendar specifier (c).
        /// </summary>
        internal static CharacterHandler <TResult, TBucket> CreateCalendarHandler <TResult, TBucket>
            (Func <TResult, CalendarSystem> getter, Action <TBucket, CalendarSystem> setter)
            where TBucket : ParseBucket <TResult>
        {
            return((pattern, builder) =>
            {
                builder.AddField(PatternFields.Calendar, pattern.Current);

                builder.AddParseAction((cursor, bucket) =>
                {
                    foreach (var id in CalendarSystem.Ids)
                    {
                        if (cursor.Match(id))
                        {
                            setter(bucket, CalendarSystem.ForId(id));
                            return null;
                        }
                    }
                    return ParseResult <TResult> .NoMatchingCalendarSystem(cursor);
                });
                builder.AddFormatAction((value, sb) => sb.Append(getter(value).Id));
            });
        }
        /// <summary>
        /// Converts the given value object to the specified type, using the specified context and culture information.
        /// </summary>
        /// <returns>
        /// An <see cref="T:System.Object"/> that represents the converted value.
        /// </returns>
        /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"/> that provides a format context. </param>
        /// <param name="culture">A <see cref="T:System.Globalization.CultureInfo"/>. If null is passed, the current culture is assumed. </param>
        /// <param name="value">The <see cref="T:System.Object"/> to convert. </param>
        /// <param name="destinationType">The <see cref="T:System.Type"/> to convert the <paramref name="value"/> parameter to. </param>
        /// <exception cref="T:System.ArgumentNullException">The <paramref name="destinationType"/> parameter is null. </exception>
        /// <exception cref="T:System.NotSupportedException">The conversion cannot be performed. </exception>
        public override object ConvertTo(
            ITypeDescriptorContext context,
            CultureInfo culture,
            [NotNull] object value,
            Type destinationType)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }
            if (destinationType == null)
            {
                throw new ArgumentNullException(nameof(destinationType));
            }

            CalendarSystem calendarSystem = (CalendarSystem)value;

            if (destinationType == typeof(string))
            {
                return(calendarSystem.Id);
            }

            return(base.ConvertTo(context, culture, value, destinationType));
        }
 protected WrappedCalendarSystem(string name, CalendarSystem baseCalendar, FieldAssembler assembler, IEnumerable<Era> eras)
     : base(name, (builder, @this) => AssembleFields(builder, @this, baseCalendar, assembler), eras)
 {
     // Quick sanity check - the point of separating out this class is to only use it in
     // situations where we really have a calendar to wrap.
     if (baseCalendar == null)
     {
         throw new ArgumentNullException("baseCalendar");
     }
     this.baseCalendar = baseCalendar;
     // Work out which fields from the base are still valid, so we can
     // optimize by calling directly to the base calendar sometimes.
     FieldSet baseFields = baseCalendar.Fields;
     useBaseTimeOfDayFields = baseFields.HourOfDay == Fields.HourOfDay && 
                                 baseFields.MinuteOfHour == Fields.MinuteOfHour &&
                                 baseFields.SecondOfMinute == Fields.SecondOfMinute && 
                                 baseFields.MillisecondOfSecond == Fields.MillisecondOfSecond &&
                                 baseFields.TickOfMillisecond == Fields.TickOfMillisecond &&
                                 baseFields.TickOfSecond == Fields.TickOfSecond;
     useBaseTickOfDayFields = baseFields.TickOfDay == Fields.TickOfDay;
     useBaseYearMonthDayFields = baseFields.Year == Fields.Year &&
                                 baseFields.MonthOfYear == Fields.MonthOfYear &&
                                 baseFields.DayOfMonth == Fields.DayOfMonth;
 }
Example #12
0
        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            graphics.PreferredBackBufferHeight = 720;
            graphics.PreferredBackBufferWidth  = 1280;
            base.Initialize();
            InputManager.AddStateProvider(typeof(KeyboardStateProvider), new KeyboardStateProvider());
            InputManager.AddStateProvider(typeof(GamepadStateProvider), new GamepadStateProvider());
            InputManager.Mapper.AddInputBindProvider(typeof(KeyInputBindProvider), new KeyInputBindProvider());
            InputManager.Mapper.AddInputBindProvider(typeof(PadInputBindProvider), new PadInputBindProvider());

            CalendarSystem calendar = new CalendarSystem(this, 15);

            Components.Add(calendar);

            WeatherSystem weatherSystem = new WeatherSystem(this);

            Components.Add(weatherSystem);

            // TODO: Debug logger.
            ScriptEngine engine = new ScriptEngine(this, Path.Combine("cfg", "sengine.cfg"));

            engine.LoggingMethod = LoggingMethod.Console;
            Components.Add(engine);

            InputManager.Mapper.GetInputBindProvider <KeyInputBindProvider>().Map(
                new KeyTrigger("Debug exit", Keys.Escape), (triggered, args) => Exit()
                );
            InputManager.Mapper.GetInputBindProvider <PadInputBindProvider>().Map(
                new ButtonTrigger("Debug exit", Buttons.Back), (triggered, args) => Exit()
                );

            Components.Add(new RepositoryManager(@"\dat\repos",
                                                 new string[] { "Farmi.Datasets." },
                                                 new string[] { "Farmi.Repositories." }));
            GameStateManager.ChangeState(new GameplayScreen());
        }
Example #13
0
        [Test, Timeout(300000)] // Can take a long time under NCrunch.
        public void BclThroughHistory()
        {
            Calendar       bcl  = new PersianCalendar();
            CalendarSystem noda = CalendarSystem.GetPersianCalendar();

            for (int year = 1; year < 9378; year++)
            {
                for (int month = 1; month < 13; month++)
                {
                    Assert.AreEqual(bcl.GetDaysInMonth(year, month), noda.GetDaysInMonth(year, month),
                                    "Year: {0}; Month: {1}", year, month);
                    for (int day = 1; day < bcl.GetDaysInMonth(year, month); day++)
                    {
                        DateTime  bclDate  = new DateTime(year, month, day, bcl);
                        LocalDate nodaDate = new LocalDate(year, month, day, noda);
                        Assert.AreEqual(bclDate, nodaDate.AtMidnight().ToDateTimeUnspecified());
                        Assert.AreEqual(nodaDate, LocalDateTime.FromDateTime(bclDate).WithCalendar(noda).Date);
                        Assert.AreEqual(year, nodaDate.Year);
                        Assert.AreEqual(month, nodaDate.Month);
                        Assert.AreEqual(day, nodaDate.Day);
                    }
                }
            }
        }
Example #14
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);
                    }
                }
            }
        }
        public void SampleDate()
        {
            CalendarSystem copticCalendar = CalendarSystem.Coptic;
            LocalDateTime  iso            = new LocalDateTime(2004, 6, 9, 0, 0, 0, 0);
            LocalDateTime  coptic         = iso.WithCalendar(copticCalendar);

            Assert.AreEqual(Era.AnnoMartyrum, coptic.Era);
            Assert.AreEqual(1720, coptic.YearOfEra);

            Assert.AreEqual(1720, coptic.Year);
            Assert.IsFalse(copticCalendar.IsLeapYear(1720));

            Assert.AreEqual(10, coptic.Month);
            Assert.AreEqual(2, coptic.Day);

            Assert.AreEqual(IsoDayOfWeek.Wednesday, coptic.IsoDayOfWeek);

            Assert.AreEqual(9 * 30 + 2, coptic.DayOfYear);

            Assert.AreEqual(0, coptic.Hour);
            Assert.AreEqual(0, coptic.Minute);
            Assert.AreEqual(0, coptic.Second);
            Assert.AreEqual(0, coptic.Millisecond);
        }
        public void AllIdsGiveDifferentCalendars()
        {
            var allCalendars = CalendarSystem.Ids.Select(id => CalendarSystem.ForId(id));

            Assert.AreEqual(CalendarSystem.Ids.Count(), allCalendars.Distinct().Count());
        }
Example #17
0
        //TODO: make sure that there is no better place for this method
        //TODO: consider making it a delegate within the enum value.

        /// <summary>
        /// Gets a suitable field for this type from the given calendar.
        /// </summary>
        /// <param name="calendar">The calendar to use</param>
        /// <returns>A suitable field</returns>
        internal DateTimeField GetField(CalendarSystem calendar)
        {
            if (calendar == null)
            {
                throw new ArgumentNullException("calendar");
            }

            //dispatch over Ordinal
            switch (Ordinal)
            {
                case 0:
                    return calendar.Fields.Era;
                case 1:
                    return calendar.Fields.YearOfEra;
                case 2:
                    return calendar.Fields.CenturyOfEra;
                case 3:
                    return calendar.Fields.YearOfCentury;
                case 4:
                    return calendar.Fields.Year;
                case 5:
                    return calendar.Fields.DayOfYear;
                case 6:
                    return calendar.Fields.MonthOfYear;
                case 7:
                    return calendar.Fields.DayOfMonth;
                case 8:
                    return calendar.Fields.WeekYearOfCentury;
                case 9:
                    return calendar.Fields.WeekYear;
                case 10:
                    return calendar.Fields.WeekOfWeekYear;
                case 11:
                    return calendar.Fields.DayOfWeek;
                case 12:
                    return calendar.Fields.HalfDayOfDay;
                case 13:
                    return calendar.Fields.HourOfHalfDay;
                case 14:
                    return calendar.Fields.ClockHourOfHalfDay;
                case 15:
                    return calendar.Fields.ClockHourOfDay;
                case 16:
                    return calendar.Fields.HourOfDay;
                case 17:
                    return calendar.Fields.MinuteOfDay;
                case 18:
                    return calendar.Fields.MinuteOfHour;
                case 19:
                    return calendar.Fields.SecondOfMinute;
                case 20:
                    return calendar.Fields.SecondOfDay;
                case 21:
                    return calendar.Fields.MillisecondOfDay;
                case 22:
                    return calendar.Fields.MillisecondOfSecond;
                case 23:
                    return calendar.Fields.TickOfMillisecond;
                case 24:
                    return calendar.Fields.TickOfDay;
                case 25:
                    return calendar.Fields.TickOfSecond;
                default:
                    throw new InvalidOperationException();
            }
        }
Example #18
0
 /// <summary>
 /// Validate that at least one day in the calendar falls in the given week year.
 /// </summary>
 private void ValidateWeekYear(int weekYear, CalendarSystem calendar)
 {
     if (weekYear > calendar.MinYear && weekYear < calendar.MaxYear)
     {
         return;
     }
     int minCalendarYearDays = GetWeekYearDaysSinceEpoch(calendar.YearMonthDayCalculator, calendar.MinYear);
     // If week year X started after calendar year X, then the first days of the calendar year are in the
     // previous week year.
     int minWeekYear = minCalendarYearDays > calendar.MinDays ? calendar.MinYear - 1 : calendar.MinYear;
     int maxCalendarYearDays = GetWeekYearDaysSinceEpoch(calendar.YearMonthDayCalculator, calendar.MaxYear + 1);
     // If week year X + 1 started after the last day in the calendar, then everything is within week year X.
     // For irregular rules, we always just use calendar.MaxYear.
     int maxWeekYear = irregularWeeks || (maxCalendarYearDays > calendar.MaxDays) ? calendar.MaxYear : calendar.MaxYear + 1;
     Preconditions.CheckArgumentRange(nameof(weekYear), weekYear, minWeekYear, maxWeekYear);
 }
Example #19
0
 public void MinDate(CalendarSystem calendar)
 {
     // Construct the smallest LocalDate we can, and validate that all the properties can be fetched without
     // issues.
     ValidateProperties(calendar, calendar.MinDays, calendar.MinYear);
 }
 /// <summary>
 /// Field assembly used solely for the ISO calendar variation.
 /// </summary>
 private static void AssembleIsoFields(FieldSet.Builder builder, CalendarSystem @this)
 {
     // Use zero based century and year of century.
     DividedDateTimeField centuryOfEra = new DividedDateTimeField(IsoYearOfEraDateTimeField.Instance, DateTimeFieldType.CenturyOfEra, 100);
     builder.CenturyOfEra = centuryOfEra;
     builder.YearOfCentury = new RemainderDateTimeField(centuryOfEra, DateTimeFieldType.YearOfCentury);
     builder.WeekYearOfCentury = new RemainderDateTimeField(centuryOfEra, DateTimeFieldType.WeekYearOfCentury);
     builder.Centuries = centuryOfEra.DurationField;
 }
Example #21
0
        public void XmlSerialization_NonIso()
        {
            var value = new OffsetDateTime(new LocalDateTime(2013, 4, 12, 17, 53, 23, CalendarSystem.GetJulianCalendar(3)),
                                           Offset.FromHours(1));

            TestHelper.AssertXmlRoundtrip(value, "<value calendar=\"Julian 3\">2013-04-12T17:53:23+01:00</value>");
        }
Example #22
0
 internal static ParseResult <T> YearOfEraOutOfRange(int value, int eraIndex, CalendarSystem calendar)
 {
     return(ForInvalidValue(Messages.Parse_YearOfEraOutOfRange, value, calendar.Eras[eraIndex].Name, calendar.Name));
 }
Example #23
0
 /// <summary>
 /// Create a new instance for <see cref="IslamicDateInfo"/><br />
 /// 创建一个 <see cref="IslamicDateInfo"/> 的新实例
 /// </summary>
 /// <param name="dt"></param>
 public IslamicDateInfo(IslamicDateTime dt)
 {
     InternalDateTime  = dt.InternalTime;
     InternalLocalDate = new LocalDate(dt.IslamicYear, dt.IslamicMonth, dt.IslamicDay, dt.InternalCalendarSystem);
     Calendar          = dt.InternalCalendarSystem;
 }
Example #24
0
 /// <summary>
 /// Creates a pattern like this one, but with the template value modified to use
 /// the specified calendar system.
 /// </summary>
 /// <remarks>
 /// <para>
 /// Care should be taken in two (relatively rare) scenarios. Although the default template value
 /// is supported by all Noda Time calendar systems, if a pattern is created with a different
 /// template value and then this method is called with a calendar system which doesn't support that
 /// date, an exception will be thrown. Additionally, if the pattern only specifies some date fields,
 /// it's possible that the new template value will not be suitable for all values.
 /// </para>
 /// </remarks>
 /// <param name="calendar">The calendar system to convert the template value into.</param>
 /// <returns>A new pattern with a template value in the specified calendar system.</returns>
 public OffsetDatePattern WithCalendar(CalendarSystem calendar) =>
 WithTemplateValue(TemplateValue.WithCalendar(calendar));
 public void ForOrdinal_Roundtrip(CalendarSystem calendar)
 {
     Assert.AreSame(calendar, CalendarSystem.ForOrdinal(calendar.Ordinal));
 }
 public void ForOrdinal_Roundtrip(CalendarSystem calendar)
 {
     Assert.AreSame(calendar, CalendarSystem.ForOrdinal(calendar.Ordinal));
 }
Example #27
0
 private static void AssembleFields(FieldSet.Builder builder, CalendarSystem @this)
 {
     builder.Era = EraField;
     builder.MonthOfYear = new BasicMonthOfYearDateTimeField((BasicCalendarSystem) @this, 12);
     builder.Months = builder.MonthOfYear.DurationField;
 }
 public void BadId()
 {
     Assert.Throws <KeyNotFoundException>(() => CalendarSystem.ForId("bad"));
 }
 private static void AssembleFields(FieldSet.Builder builder, CalendarSystem @this, CalendarSystem baseCalendar, FieldAssembler assembler)
 {
     builder.WithSupportedFieldsFrom(baseCalendar.Fields);
     assembler(builder, @this);
 }
 internal LocalDateParseBucket(LocalDate templateValue)
 {
     this.templateValue = templateValue;
     // Only fetch this once.
     this.Calendar = templateValue.Calendar;
 }
Example #31
0
 public void GetInstance_UniqueIds()
 {
     Assert.AreEqual(7, Enumerable.Range(1, 7).Select(x => CalendarSystem.GetGregorianCalendar(x).Id).Distinct().Count());
 }
        private static void AssembleFields(FieldSet.Builder builder, CalendarSystem @this)
        {
            // None of the fields will call anything on the calendar system *yet*, so this is safe enough.
            BasicCalendarSystem thisCalendar = (BasicCalendarSystem) @this;
            // First copy the fields that are the same for all basic
            // calendars
            builder.WithSupportedFieldsFrom(preciseFields);

            // Now create fields that have unique behavior for Gregorian and Julian
            // calendars.

            builder.Year = new BasicYearDateTimeField(thisCalendar);
            builder.YearOfEra = new GJYearOfEraDateTimeField(builder.Year, thisCalendar);

            // Define one-based centuryOfEra and yearOfCentury.
            DateTimeField field = new OffsetDateTimeField(builder.YearOfEra, 99);
            builder.CenturyOfEra = new DividedDateTimeField(field, DateTimeFieldType.CenturyOfEra, 100);

            field = new RemainderDateTimeField((DividedDateTimeField)builder.CenturyOfEra);
            builder.YearOfCentury = new OffsetDateTimeField(field, DateTimeFieldType.YearOfCentury, 1);

            builder.Era = new GJEraDateTimeField(thisCalendar);
            builder.DayOfWeek = new GJDayOfWeekDateTimeField(thisCalendar, builder.Days);
            builder.DayOfMonth = new BasicDayOfMonthDateTimeField(thisCalendar, builder.Days);
            builder.DayOfYear = new BasicDayOfYearDateTimeField(thisCalendar, builder.Days);
            builder.MonthOfYear = new BasicMonthOfYearDateTimeField(thisCalendar, 2); // February is the leap month
            builder.WeekYear = new BasicWeekYearDateTimeField(thisCalendar);
            builder.WeekOfWeekYear = new BasicWeekOfWeekYearDateTimeField(thisCalendar, builder.Weeks);

            field = new RemainderDateTimeField(builder.WeekYear, DateTimeFieldType.WeekYearOfCentury, 100);
            builder.WeekYearOfCentury = new OffsetDateTimeField(field, DateTimeFieldType.WeekYearOfCentury, 1);
            // The remaining (imprecise) durations are available from the newly
            // created datetime fields.

            builder.Years = builder.Year.DurationField;
            builder.Centuries = builder.CenturyOfEra.DurationField;
            builder.Months = builder.MonthOfYear.DurationField;
            builder.WeekYears = builder.WeekYear.DurationField;
        }
Example #33
0
 public void GetInstance_InvalidMinDaysInFirstWeek()
 {
     Assert.Throws <ArgumentOutOfRangeException>(() => CalendarSystem.GetGregorianCalendar(0));
     Assert.Throws <ArgumentOutOfRangeException>(() => CalendarSystem.GetGregorianCalendar(8));
 }
Example #34
0
 public static ZonedClock InZone([NotNull] this IClock clock,
                                 [NotNull] DateTimeZone zone,
                                 [NotNull] CalendarSystem calendar) => new ZonedClock(clock, zone, calendar);
Example #35
0
 /// <summary>
 /// Creates a pattern like this one, but with the template value modified to use
 /// the specified calendar system.
 /// </summary>
 /// <remarks>
 /// <para>
 /// Care should be taken in two (relatively rare) scenarios. Although the default template value
 /// is supported by all Noda Time calendar systems, if a pattern is created with a different
 /// template value and then this method is called with a calendar system which doesn't support that
 /// date, an exception will be thrown. Additionally, if the pattern only specifies some date fields,
 /// it's possible that the new template value will not be suitable for all values.
 /// </para>
 /// </remarks>
 /// <param name="calendar">The calendar system to convert the template value into.</param>
 /// <returns>A new pattern with a template value in the specified calendar system.</returns>
 [NotNull] public LocalDatePattern WithCalendar([NotNull] CalendarSystem calendar) =>
 WithTemplateValue(TemplateValue.WithCalendar(calendar));
Example #36
0
        /// <inheritdoc />
        public LocalDate GetLocalDate(int weekYear, int weekOfWeekYear, IsoDayOfWeek dayOfWeek, CalendarSystem calendar)
        {
            Preconditions.CheckNotNull(calendar, nameof(calendar));
            ValidateWeekYear(weekYear, calendar);

            // The actual message for this won't be ideal, but it's clear enough.
            Preconditions.CheckArgumentRange(nameof(dayOfWeek), (int)dayOfWeek, 1, 7);

            var yearMonthDayCalculator = calendar.YearMonthDayCalculator;
            var maxWeeks = GetWeeksInWeekYear(weekYear, calendar);

            if (weekOfWeekYear < 1 || weekOfWeekYear > maxWeeks)
            {
                throw new ArgumentOutOfRangeException(nameof(weekOfWeekYear));
            }

            unchecked
            {
                int startOfWeekYear = GetWeekYearDaysSinceEpoch(yearMonthDayCalculator, weekYear);
                // 0 for "already on the first day of the week" up to 6 "it's the last day of the week".
                int daysIntoWeek = ((dayOfWeek - firstDayOfWeek) + 7) % 7;
                int days         = startOfWeekYear + (weekOfWeekYear - 1) * 7 + daysIntoWeek;
                if (days < calendar.MinDays || days > calendar.MaxDays)
                {
                    throw new ArgumentOutOfRangeException(nameof(weekYear),
                                                          $"The combination of {nameof(weekYear)}, {nameof(weekOfWeekYear)} and {nameof(dayOfWeek)} is invalid");
                }
                LocalDate ret = new LocalDate(yearMonthDayCalculator.GetYearMonthDay(days).WithCalendar(calendar));

                // For rules with irregular weeks, the calculation so far may end up computing a date which isn't
                // in the right week-year. This will happen if the caller has specified a "short" week (i.e. one
                // at the start or end of the week-year which is not seven days long due to the week year changing
                // part way through a week) and a day-of-week which corresponds to the "missing" part of the week.
                // Examples are in SimpleWeekYearRuleTest.GetLocalDate_Invalid.
                // The simplest way to find out is just to check what the week year is, but we only need to do
                // the full check if the requested week-year is different to the calendar year of the result.
                // We don't need to check for this in regular rules, because the computation we've already performed
                // will always be right.
                if (irregularWeeks && weekYear != ret.Year)
                {
                    if (GetWeekYear(ret) != weekYear)
                    {
                        throw new ArgumentOutOfRangeException(nameof(weekYear),
                                                              $"The combination of {nameof(weekYear)}, {nameof(weekOfWeekYear)} and {nameof(dayOfWeek)} is invalid");
                    }
                }
                return(ret);
            }
        }
Example #37
0
 /// <summary>
 /// Create a new instance of <see cref="IslamicDateInfo"/><br />
 /// 创建一个新的 <see cref="IslamicDateInfo"/> 实例。
 /// </summary>
 /// <param name="year"></param>
 /// <param name="month"></param>
 /// <param name="day"></param>
 /// <param name="calendar"></param>
 /// <returns></returns>
 public static IslamicDateInfo Of(int year, int month, int day, CalendarSystem calendar = null)
 {
     return(new(DateTimeFactory.Create(year, month, day), calendar ?? _islamicCalendar));
 }
 public void ValidId(string id)
 {
     Assert.IsInstanceOf <CalendarSystem>(CalendarSystem.ForId(id));
 }
 internal static void AssertEquivalent(Calendar bcl, CalendarSystem noda)
 {
     AssertEquivalent(bcl, noda, noda.MinYear, noda.MaxYear);
 }
Example #40
0
 public Data(int year, int month, int day, CalendarSystem calendar)
     : this(new LocalDate(year, month, day, calendar))
 {
 }
 public void IdsAreCaseSensitive(string id)
 {
     Assert.Throws <KeyNotFoundException>(() => CalendarSystem.ForId(id.ToLowerInvariant()));
 }
Example #42
0
        /// <summary>
        /// Create a new instance of <see cref="IslamicDateInfo"/><br />
        /// 创建一个新的 <see cref="IslamicDateInfo"/> 实例。
        /// </summary>
        /// <param name="year"></param>
        /// <param name="month"></param>
        /// <param name="day"></param>
        /// <param name="calendar"></param>
        /// <returns></returns>
        public static IslamicDateInfo OfLunar(int year, int month, int day, CalendarSystem calendar = null)
        {
            var ld = new LocalDate(year, month, day, calendar ?? _islamicCalendar);

            return(new IslamicDateInfo(ld));
        }
Example #43
0
 public void MinDate(CalendarSystem calendar)
 {
     // Construct the smallest LocalDate we can, and validate that all the properties can be fetched without
     // issues.
     ValidateProperties(calendar, calendar.MinDays, calendar.MinYear);
 }
Example #44
0
 private IslamicDateInfo(LocalDate ld)
 {
     InternalDateTime  = ld.ToDateTimeUnspecified();
     InternalLocalDate = ld;
     Calendar          = ld.Calendar;
 }
 /// <summary>
 /// Creates a pattern like this one, but with the template value modified to use
 /// the specified calendar system.
 /// </summary>
 /// <remarks>
 /// <para>
 /// Care should be taken in two (relatively rare) scenarios. Although the default template value
 /// is supported by all Noda Time calendar systems, if a pattern is created with a different
 /// template value and then this method is called with a calendar system which doesn't support that
 /// date, an exception will be thrown. Additionally, if the pattern only specifies some date fields,
 /// it's possible that the new template value will not be suitable for all values.
 /// </para>
 /// </remarks>
 /// <param name="calendar">The calendar system to convert the template value into.</param>
 /// <returns>A new pattern with a template value in the specified calendar system.</returns>
 public OffsetDateTimePattern WithCalendar([NotNull] CalendarSystem calendar) =>
 WithTemplateValue(TemplateValue.WithCalendar(calendar));