Esempio n. 1
0
        /// Returns UTC DateTime with Kind.Unspecified
        public static DateTime ConvertToUtcWithUncpecifiedKind(this DateTime dateTime, string tzFrom) {
            string tz;
            if (!Normalizer.TryGetValue(tzFrom.ToLowerInvariant(), out tz)) {
                tz = tzFrom;
            }
            //tz = tz.ToLowerInvariant();
            if (tz.ToLowerInvariant() == "utc") {
                if (dateTime.Kind == DateTimeKind.Local) throw new ArgumentException("Cannot treat local time as Utc, please specify kind = Utc or Uncpecified");
                return DateTime.SpecifyKind(dateTime, DateTimeKind.Unspecified);
            }
            var utcTimeZone = DateTimeZoneProviders.Tzdb["UTC"];
            var givenTz = DateTimeZoneProviders.Tzdb[tz];
            var tickWithinSecond = (int) (dateTime.Ticks%TimeSpan.TicksPerSecond);
            var millis = tickWithinSecond / 10000;
            var tickWithinMillis = tickWithinSecond % 10000;

            var timeToConvert = new LocalDateTime(dateTime.Year,
                    dateTime.Month,
                    dateTime.Day,
                    dateTime.Hour,
                    dateTime.Minute, 
                    dateTime.Second,
                    millis,
                    tickWithinMillis
                ).InZoneStrictly(givenTz); ;
            DateTime utcTime = timeToConvert.ToDateTimeUtc();
            return DateTime.SpecifyKind(utcTime, DateTimeKind.Unspecified);
        }
Esempio n. 2
0
 public void AddFourYearsOnLeapDay()
 {
     LocalDateTime start = new LocalDateTime(2012, 2, 29, 10, 0);
     LocalDateTime result = start + Period.FromYears(4);
     // Feb 29th is still valid in 2016
     Assert.AreEqual(new LocalDateTime(2016, 2, 29, 10, 0), result);
 }
 public void UnixEpoch()
 {
     CalendarSystem coptic = CalendarSystem.GetCopticCalendar(4);
     LocalDateTime unixEpochInCopticCalendar = new LocalDateTime(LocalInstant.LocalUnixEpoch, coptic);
     LocalDateTime expected = new LocalDateTime(1686, 4, 23, 0, 0, coptic);
     Assert.AreEqual(expected, unixEpochInCopticCalendar);
 }
 public void Epoch()
 {
     LocalDateTime julianEpoch = new LocalDateTime(LocalInstant.LocalUnixEpoch, Julian);
     Assert.AreEqual(1969, julianEpoch.Year);
     Assert.AreEqual(12, julianEpoch.MonthOfYear);
     Assert.AreEqual(19, julianEpoch.DayOfMonth);
 }
 public void EraProperty()
 {
     CalendarSystem calendar = CalendarSystem.Gregorian;
     LocalDateTime startOfEra = new LocalDateTime(1, 1, 1, 0, 0, 0, calendar);
     Assert.AreEqual(Era.Common, startOfEra.Era);
     Assert.AreEqual(Era.BeforeCommon, startOfEra.PlusTicks(-1).Era);
 }
        public void FieldsOf_GreatAchievement()
        {
            LocalDateTime now = new LocalDateTime(new LocalInstant((TimeOfGreatAchievement - UnixEpochDateTime).Ticks), CalendarSystem.Iso);

            Assert.AreEqual(2009, now.Year);
            Assert.AreEqual(2009, now.YearOfEra);
            Assert.AreEqual(9, now.YearOfCentury);
            Assert.AreEqual(20, now.CenturyOfEra);
            Assert.AreEqual(2009, now.WeekYear);
            Assert.AreEqual(48, now.WeekOfWeekYear);
            Assert.AreEqual(11, now.MonthOfYear);
            Assert.AreEqual(27, now.DayOfMonth);
            Assert.AreEqual(TimeOfGreatAchievement.DayOfYear, now.DayOfYear);
            Assert.AreEqual(IsoDayOfWeek.Friday, now.IsoDayOfWeek);
            Assert.AreEqual(5, now.DayOfWeek);
            Assert.AreEqual(Era.Common, now.Era);
            Assert.AreEqual(18, now.HourOfDay);
            Assert.AreEqual(38, now.MinuteOfHour);
            Assert.AreEqual(25, now.SecondOfMinute);
            Assert.AreEqual((18 * 60 * 60) + (38 * 60) + 25, now.SecondOfDay);
            Assert.AreEqual(345, now.MillisecondOfSecond);
            Assert.AreEqual(345 + now.SecondOfDay * 1000, now.MillisecondOfDay);
            Assert.AreEqual(now.MillisecondOfDay * 10000L + 8765, now.TickOfDay);
            Assert.AreEqual(8765, now.TickOfMillisecond);
            Assert.AreEqual(3458765, now.TickOfSecond);
        }
 public void GetOccurrenceForYear_Defaults_Epoch()
 {
     var offset = new ZoneYearOffset(TransitionMode.Utc, 1, 1, 0, true, LocalTime.Midnight);
     var actual = offset.GetOccurrenceForYear(1970);
     var expected = new LocalDateTime(1970, 1, 1, 0, 0).ToLocalInstant();
     Assert.AreEqual(expected, actual);
 }
Esempio n. 8
0
        public void AddMilliseconds_Arround3Days_AreEqual()
        {
            var act = TestStruct.AddMilliseconds(3 * 24 * 60 * 60 * 1003);
            var exp = new LocalDateTime(1988, 06, 16, 22, 23, 02, 601);

            Assert.AreEqual(exp, act);
        }
Esempio n. 9
0
        public void AddMinutes_2280_AreEqual()
        {
            var act = TestStruct.AddMinutes(2 * 24 * 60);
            var exp = new LocalDateTime(1988, 06, 15, 22, 10, 05, 001);

            Assert.AreEqual(exp, act);
        }
 public void UnixEpoch()
 {
     CalendarSystem coptic = CalendarSystem.Coptic;
     LocalDateTime unixEpochInCopticCalendar = NodaConstants.UnixEpoch.InZone(DateTimeZone.Utc, coptic).LocalDateTime;
     LocalDateTime expected = new LocalDateTime(1686, 4, 23, 0, 0, coptic);
     Assert.AreEqual(expected, unixEpochInCopticCalendar);
 }
Esempio n. 11
0
        public void AddHours_41_AreEqual()
        {
            var act = TestStruct.AddHours(41);
            var exp = new LocalDateTime(1988, 06, 15, 15, 10, 05, 001);

            Assert.AreEqual(exp, act);
        }
Esempio n. 12
0
 public void AddOneYearOnLeapDay()
 {
     LocalDateTime start = new LocalDateTime(2012, 2, 29, 10, 0);
     LocalDateTime result = start + Period.FromYears(1);
     // Feb 29th becomes Feb 28th
     Assert.AreEqual(new LocalDateTime(2013, 2, 28, 10, 0), result);
 }
 public Answer GetAnswer(Question question)
 {
     var cityToken = question.GetToken<CityToken>();
     var dateToken = question.GetToken<DateToken>();
     int? year = null;
     if (dateToken != null) year = dateToken.Year;
     DaylightSavingInformation daylightSavingInfo;
     if (year.HasValue)
     {
         var firstDateInTheYear = new LocalDateTime(year.Value, 1, 1, 0, 0).InZone(DateTimeZoneProviders.Tzdb[cityToken.City.Timezone], Resolvers.LenientResolver);
         var firstZoneIntervalInTheYear = firstDateInTheYear.GetZoneInterval();
         if (firstZoneIntervalInTheYear.IsoLocalEnd.Year > 10000) {
             daylightSavingInfo = DaylightSavingInformation.CreateWithNoDaylightSavings();
         }
         else
         {
             var firstDateInTheNextZoneInterval = firstDateInTheYear.Plus(firstZoneIntervalInTheYear.Duration).Plus(Duration.FromMilliseconds(1));
             daylightSavingInfo = GetDaylightSavingInfo(firstDateInTheNextZoneInterval);
         }
     }
     else
     {
         daylightSavingInfo = GetDaylightSavingInfo(cityToken.GetCurrentTime());
     }
     var answerText = GetFormattedDaylightSavingInfo(daylightSavingInfo, cityToken.City);
     return new Answer(question, true, true, answerText);
 }
        public void FieldsOf_UnixEpoch()
        {
            // It's easiest to test this using a LocalDateTime in the ISO calendar system.
            // LocalDateTime just passes everything through anyway.
            LocalDateTime epoch = new LocalDateTime(LocalInstant.LocalUnixEpoch, CalendarSystem.Iso);

            Assert.AreEqual(1970, epoch.Year);
            Assert.AreEqual(1970, epoch.YearOfEra);
            Assert.AreEqual(70, epoch.YearOfCentury);
            Assert.AreEqual(19, epoch.CenturyOfEra);
            Assert.AreEqual(1970, epoch.WeekYear);
            Assert.AreEqual(1, epoch.WeekOfWeekYear);
            Assert.AreEqual(1, epoch.MonthOfYear);
            Assert.AreEqual(1, epoch.DayOfMonth);
            Assert.AreEqual(1, epoch.DayOfYear);
            Assert.AreEqual(IsoDayOfWeek.Thursday, epoch.IsoDayOfWeek);
            Assert.AreEqual(4, epoch.DayOfWeek);
            Assert.AreEqual(Era.Common, epoch.Era);
            Assert.AreEqual(0, epoch.HourOfDay);
            Assert.AreEqual(0, epoch.MinuteOfHour);
            Assert.AreEqual(0, epoch.SecondOfMinute);
            Assert.AreEqual(0, epoch.SecondOfDay);
            Assert.AreEqual(0, epoch.MillisecondOfSecond);
            Assert.AreEqual(0, epoch.MillisecondOfDay);
            Assert.AreEqual(0, epoch.TickOfDay);
            Assert.AreEqual(0, epoch.TickOfMillisecond);
            Assert.AreEqual(0, epoch.TickOfSecond);
        }
        public void SampleDate()
        {
            CalendarSystem copticCalendar = CalendarSystem.GetCopticCalendar(4);
            LocalDateTime iso = new LocalDateTime(2004, 6, 9, 0, 0, 0, 0);
            LocalDateTime coptic = new LocalDateTime(iso.LocalInstant, copticCalendar);

            Assert.AreEqual(Era.AnnoMartyrm, coptic.Era);
            Assert.AreEqual(18, coptic.CenturyOfEra);
            Assert.AreEqual(20, coptic.YearOfCentury);
            Assert.AreEqual(1720, coptic.YearOfEra);

            Assert.AreEqual(1720, coptic.Year);
            Assert.IsFalse(copticCalendar.IsLeapYear(1720));
        
            Assert.AreEqual(10, coptic.MonthOfYear);
            Assert.AreEqual(2, coptic.DayOfMonth);
            
            // TODO: Determine whether we should consider the Coptic calendar to use ISO
            // days of the week.
            Assert.AreEqual(IsoDayOfWeek.Wednesday, coptic.IsoDayOfWeek);

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

            Assert.AreEqual(0, coptic.HourOfDay);
            Assert.AreEqual(0, coptic.MinuteOfHour);
            Assert.AreEqual(0, coptic.SecondOfMinute);
            Assert.AreEqual(0, coptic.MillisecondOfSecond);
            Assert.AreEqual(0, coptic.TickOfMillisecond);
        }
Esempio n. 16
0
 public void ComputedProperties()
 {
     LocalDateTime start = new LocalDateTime(2011, 6, 3, 19, 15);
     LocalDateTime end = new LocalDateTime(2011, 8, 2, 22, 45);
     Assert.AreEqual(start, SampleInterval.IsoLocalStart);
     Assert.AreEqual(end, SampleInterval.IsoLocalEnd);
     Assert.AreEqual(SampleEnd - SampleStart, SampleInterval.Duration);
 }
Esempio n. 17
0
        public void LocalDateTimeProperty()
        {
            LocalDateTime local = new LocalDateTime(2012, 6, 19, 1, 2, 3, 4, 5, CalendarSystem.Julian);
            Offset offset = Offset.FromHours(5);

            OffsetDateTime odt = new OffsetDateTime(local, offset);
            Assert.AreEqual(local, odt.LocalDateTime);
        }
Esempio n. 18
0
 public void JulianEpoch()
 {
     // Compute the Julian epoch using the Julian calendar, instead of the
     // Gregorian version.
     var localEpoch = new LocalDateTime(-4712, 1, 1, 12, 0, CalendarSystem.Julian);
     var epoch = localEpoch.InZoneStrictly(DateTimeZone.Utc).ToInstant();
     Assert.AreEqual(epoch, NodaConstants.JulianEpoch);
 }
Esempio n. 19
0
        public void TimeOfDay_After1970()
        {
            LocalDateTime dateTime = new LocalDateTime(1975, 11, 8, 12, 5, 23);
            LocalTime expected = new LocalTime(12, 5, 23);
            Assert.AreEqual(expected, dateTime.TimeOfDay);

            Assert.AreEqual(new LocalDateTime(1970, 1, 1, 12, 5, 23), dateTime.TimeOfDay.LocalDateTime);
        }
Esempio n. 20
0
 internal LocalDateTime Add(LocalDateTime start, long units)
 {
     int extraDays = 0;
     LocalTime time = Add(start.TimeOfDay, units, ref extraDays);
     // Even though PlusDays optimizes for "value == 0", it's still quicker not to call it.
     LocalDate date = extraDays == 0 ? start.Date :  start.Date.PlusDays(extraDays);
     return new LocalDateTime(date, time);
 }
 public DateTime DateTimeWithOlsenZoneToUtc(DateTime dateTime, string olsenTimeZone)
 {
     var dateTimeZoneProvider = DateTimeZoneProviders.Tzdb;
     var dateTimeZone = dateTimeZoneProvider[olsenTimeZone];
     var startTime = dateTime;
     var localDateTime = new LocalDateTime(startTime.Year, startTime.Month, startTime.Day, startTime.Hour, startTime.Minute);
     return dateTimeZone.AtLeniently(localDateTime).ToDateTimeUtc();
 }
Esempio n. 22
0
 public Zinsfestschreibung(LocalDateTime festschreibung, LocalDateTime auslauf, double zinssatz)
     : this()
 {
     this.ZeitpunktFestschreibung = festschreibung;
     this.ZeitpunktAuslauf = auslauf;
     this.Zinssatz = zinssatz;
     ////this.ZeitraumFestschreibungZinstage = (int)(Period.Between(this.ZeitpunktFestschreibung, this.ZeitpunktAuslauf).Days);
 }
        public void PlusDays_Simple()
        {
            LocalDateTime start = new LocalDateTime(2011, 1, 15, 12, 15, 8);
            LocalDateTime expected = new LocalDateTime(2011, 1, 23, 12, 15, 8);
            Assert.AreEqual(expected, start.PlusDays(8));

            expected = new LocalDateTime(2011, 1, 7, 12, 15, 8);
            Assert.AreEqual(expected, start.PlusDays(-8));
        }
 public void instant_as_local_time() {
     // "America/New_York"
     var est = DateTimeZoneProviders.Tzdb["America/New_York"];
     _output.WriteLine(est.ToJson());
     var localDateTime = new LocalDateTime(2016, 1, 21, 20, 6);
     _output.WriteLine(localDateTime.ToString());
     var estDateTime = est.AtStrictly(localDateTime);
     Assert.Equal("2016-01-21T20:06:00 America/New_York (-05)", estDateTime.ToString());
 }
 public void ConstructLocalInstant_WithAllFields()
 {
     LocalInstant localAchievement = new LocalDateTime(2009, 11, 27, 18, 38, 25, 345, 8765).ToLocalInstant();
     long bclTicks = (TimeOfGreatAchievement - UnixEpochDateTime).Ticks;
     int bclDays = (int) (bclTicks / NodaConstants.TicksPerDay);
     long bclTickOfDay = bclTicks % NodaConstants.TicksPerDay;
     Assert.AreEqual(bclDays, localAchievement.DaysSinceEpoch);
     Assert.AreEqual(bclTickOfDay, localAchievement.NanosecondOfDay / NodaConstants.NanosecondsPerTick);
 }
Esempio n. 26
0
        public void ToInstant()
        {
            Instant instant = Instant.FromUtc(2012, 6, 25, 16, 5, 20);
            LocalDateTime local = new LocalDateTime(2012, 6, 25, 21, 35, 20);
            Offset offset = Offset.FromHoursAndMinutes(5, 30);

            OffsetDateTime odt = new OffsetDateTime(local, offset);
            Assert.AreEqual(instant, odt.ToInstant());
        }
Esempio n. 27
0
 public void WithCalendar()
 {
     LocalDateTime isoEpoch = new LocalDateTime(1970, 1, 1, 0, 0, 0);
     LocalDateTime julianEpoch = isoEpoch.WithCalendar(CalendarSystem.GetJulianCalendar(4));
     Assert.AreEqual(1969, julianEpoch.Year);
     Assert.AreEqual(12, julianEpoch.MonthOfYear);
     Assert.AreEqual(19, julianEpoch.DayOfMonth);
     Assert.AreEqual(isoEpoch.TimeOfDay, julianEpoch.TimeOfDay);
 }
        public void PlusYear_LeapToNonLeap()
        {
            LocalDateTime start = new LocalDateTime(2012, 2, 29, 12, 15, 8);
            LocalDateTime expected = new LocalDateTime(2013, 2, 28, 12, 15, 8);
            Assert.AreEqual(expected, start.PlusYears(1));

            expected = new LocalDateTime(2011, 2, 28, 12, 15, 8);
            Assert.AreEqual(expected, start.PlusYears(-1));
        }
        public void PlusYear_Simple()
        {
            LocalDateTime start = new LocalDateTime(2011, 6, 26, 12, 15, 8);
            LocalDateTime expected = new LocalDateTime(2016, 6, 26, 12, 15, 8);
            Assert.AreEqual(expected, start.PlusYears(5));

            expected = new LocalDateTime(2006, 6, 26, 12, 15, 8);
            Assert.AreEqual(expected, start.PlusYears(-5));
        }
Esempio n. 30
0
 public void ToDateTimeUnspecified()
 {
     LocalDateTime zoned = new LocalDateTime(2011, 3, 5, 1, 0, 0);
     DateTime expected = new DateTime(2011, 3, 5, 1, 0, 0, DateTimeKind.Unspecified);
     DateTime actual = zoned.ToDateTimeUnspecified();
     Assert.AreEqual(expected, actual);
     // Kind isn't checked by Equals...
     Assert.AreEqual(DateTimeKind.Unspecified, actual.Kind);
 }
Esempio n. 31
0
 public LocalDateTime FromDateTime() => LocalDateTime.FromDateTime(SampleDateTime);
Esempio n. 32
0
        public void XmlSerialization_Iso()
        {
            var value = new LocalDateTime(2013, 4, 12, 17, 53, 23).PlusNanoseconds(123456789);

            TestHelper.AssertXmlRoundtrip(value, "<value>2013-04-12T17:53:23.123456789</value>");
        }
Esempio n. 33
0
        public void InZoneStrictly_ThrowsWhenSkipped()
        {
            var local = new LocalDateTime(2009, 3, 8, 2, 30, 0);

            Assert.Throws <SkippedTimeException>(() => local.InZoneStrictly(Pacific));
        }
        /// <summary>
        /// Populate with values based on the specified array
        /// of value types, repeating the types in cycle.
        /// </summary>
        private void PopulateValues(VariantType[] valueTypes, VariantMatrix result)
        {
            // Initial values to populate the data
            int           stringValueAsInt   = 0;
            bool          boolValue          = false;
            int           intValue           = 0;
            long          longValue          = 0;
            double        doubleValue        = 0.5;
            LocalDate     localDateValue     = new LocalDate(2003, 5, 1);
            LocalTime     localTimeValue     = new LocalTime(10, 15, 30);
            LocalMinute   localMinuteValue   = new LocalMinute(10, 15);
            LocalDateTime localDateTimeValue = new LocalDateTime(2003, 5, 1, 10, 15, 0);
            Instant       instantValue       = new LocalDateTime(2003, 5, 1, 10, 15, 0).ToInstant(DateTimeZone.Utc);

            int valueTypeCount = valueTypes.Length;

            for (int rowIndex = 0; rowIndex < result.RowCount; rowIndex++)
            {
                for (int colIndex = 0; colIndex < result.ColCount; colIndex++)
                {
                    // Repeat value types in cycle
                    var valueType = valueTypes[colIndex % valueTypeCount];
                    switch (valueType)
                    {
                    case VariantType.String:
                        result[rowIndex, colIndex] = $"Str{stringValueAsInt++}";
                        break;

                    case VariantType.Double:
                        result[rowIndex, colIndex] = doubleValue++;
                        break;

                    case VariantType.Bool:
                        result[rowIndex, colIndex] = boolValue;
                        boolValue = !boolValue;
                        break;

                    case VariantType.Int:
                        result[rowIndex, colIndex] = intValue++;
                        break;

                    case VariantType.Long:
                        result[rowIndex, colIndex] = longValue++;
                        break;

                    case VariantType.LocalDate:
                        result[rowIndex, colIndex] = localDateValue;
                        localDateValue             = localDateValue.PlusDays(1);
                        break;

                    case VariantType.LocalTime:
                        result[rowIndex, colIndex] = localTimeValue;
                        localTimeValue             = localTimeValue.PlusHours(1);
                        break;

                    case VariantType.LocalMinute:
                        result[rowIndex, colIndex] = localMinuteValue;
                        localMinuteValue           = localMinuteValue.ToLocalTime().PlusHours(1).ToLocalMinute();
                        break;

                    case VariantType.LocalDateTime:
                        result[rowIndex, colIndex] = localDateTimeValue;
                        localDateTimeValue         = localDateTimeValue.PlusDays(2).PlusHours(2);
                        break;

                    case VariantType.Instant:
                        result[rowIndex, colIndex] = instantValue;
                        instantValue = instantValue;     // TODO Fix, uses previous value
                        break;

                    default: throw new Exception($"Value type {valueType} cannot be stored in VariantMatrix.");
                    }
                }
            }
        }
 public static DateTime ToDateTime(this LocalDateTime dt)
 {
     return(new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, dt.Millisecond));
 }
Esempio n. 36
0
 public LocalDateTime FromDateTime_WithCalendar() => LocalDateTime.FromDateTime(SampleDateTime, CalendarSystem.Julian);
Esempio n. 37
0
 public static DateTime Resolve(LocalDateTime value)
 {
     return(value.ToDateTimeUnspecified());
 }
        /// <summary>
        /// Updates a finish's price table entry
        /// </summary>
        /// <param name="modelView">model view containing updatable information</param>
        /// <returns>True if the update is successful</returns>
        public static GetMaterialFinishPriceModelView update(UpdateFinishPriceTableEntryModelView modelView, IHttpClientFactory clientFactory)
        {
            string             defaultCurrency    = CurrencyPerAreaConversionService.getBaseCurrency();
            string             defaultArea        = CurrencyPerAreaConversionService.getBaseArea();
            MaterialRepository materialRepository = PersistenceContext.repositories().createMaterialRepository();
            long materialId = modelView.entityId;

            bool performedAtLeastOneUpdate = false;

            Material material = materialRepository.find(materialId);

            if (material == null)
            {
                throw new ResourceNotFoundException(MATERIAL_NOT_FOUND);
            }

            foreach (Finish finish in material.Finishes)
            {
                if (finish.Id == modelView.finishId)
                {
                    FinishPriceTableRepository finishPriceTableRepository = PersistenceContext.repositories().createFinishPriceTableRepository();
                    long finishPriceTableEntryId = modelView.tableEntryId;

                    FinishPriceTableEntry tableEntryToUpdate = finishPriceTableRepository.find(finishPriceTableEntryId);

                    if (tableEntryToUpdate == null)
                    {
                        throw new ResourceNotFoundException(ENTRY_NOT_FOUND);
                    }

                    if (tableEntryToUpdate.entity.Id != modelView.finishId)
                    {
                        throw new InvalidOperationException(ENTRY_DOESNT_BELONG_TO_FINISH);
                    }

                    LocalDateTime currentTime = NodaTime.LocalDateTime.FromDateTime(SystemClock.Instance.GetCurrentInstant().ToDateTimeUtc());

                    if (modelView.priceTableEntry.startingDate != null && LocalDateTimePattern.GeneralIso.Format(tableEntryToUpdate.timePeriod.startingDate).Equals(modelView.priceTableEntry.startingDate))
                    {
                        if (tableEntryToUpdate.timePeriod.startingDate.CompareTo(currentTime) < 0)
                        {
                            throw new InvalidOperationException(PAST_DATE);
                        }
                    }

                    if (modelView.priceTableEntry.endingDate != null && LocalDateTimePattern.GeneralIso.Format(tableEntryToUpdate.timePeriod.endingDate).Equals(modelView.priceTableEntry.endingDate))
                    {
                        if (tableEntryToUpdate.timePeriod.endingDate.CompareTo(currentTime) < 0)
                        {
                            throw new InvalidOperationException(PAST_DATE);
                        }
                    }

                    if (modelView.priceTableEntry.price != null)
                    {
                        CurrenciesService.checkCurrencySupport(modelView.priceTableEntry.price.currency);
                        AreasService.checkAreaSupport(modelView.priceTableEntry.price.area);

                        Price newPrice = null;
                        try
                        {
                            if (defaultCurrency.Equals(modelView.priceTableEntry.price.currency) && defaultArea.Equals(modelView.priceTableEntry.price.area))
                            {
                                newPrice = Price.valueOf(modelView.priceTableEntry.price.value);
                            }
                            else
                            {
                                Task <double> convertedValueTask = new CurrencyPerAreaConversionService(clientFactory)
                                                                   .convertCurrencyPerAreaToDefaultCurrencyPerArea(
                                    modelView.priceTableEntry.price.currency,
                                    modelView.priceTableEntry.price.area,
                                    modelView.priceTableEntry.price.value);
                                convertedValueTask.Wait();
                                double convertedValue = convertedValueTask.Result;
                                newPrice = Price.valueOf(convertedValue);
                            }
                        }
                        catch (HttpRequestException)
                        {
                            newPrice = Price.valueOf(modelView.priceTableEntry.price.value);
                        }

                        tableEntryToUpdate.changePrice(newPrice);
                        performedAtLeastOneUpdate = true;
                    }

                    if (modelView.priceTableEntry.endingDate != null)
                    {
                        LocalDateTime newEndingDate;
                        try
                        {
                            string newEndingDateAsString = modelView.priceTableEntry.endingDate;
                            newEndingDate = LocalDateTimePattern.GeneralIso.Parse(newEndingDateAsString).GetValueOrThrow();
                            tableEntryToUpdate.changeTimePeriod(TimePeriod.valueOf(tableEntryToUpdate.timePeriod.startingDate, newEndingDate));
                            performedAtLeastOneUpdate = true;
                        }
                        catch (UnparsableValueException)
                        {
                            throw new UnparsableValueException(DATES_WRONG_FORMAT + LocalDateTimePattern.GeneralIso.PatternText);
                        }
                    }

                    if (modelView.priceTableEntry.startingDate != null)
                    {
                        LocalDateTime newStartingDate;
                        try
                        {
                            string newStartingDateAsString = modelView.priceTableEntry.startingDate;
                            newStartingDate = LocalDateTimePattern.GeneralIso.Parse(newStartingDateAsString).GetValueOrThrow();
                            tableEntryToUpdate.changeTimePeriod(TimePeriod.valueOf(newStartingDate, tableEntryToUpdate.timePeriod.endingDate));
                            performedAtLeastOneUpdate = true;
                        }
                        catch (UnparsableValueException)
                        {
                            throw new UnparsableValueException(DATES_WRONG_FORMAT + LocalDateTimePattern.GeneralIso.PatternText);
                        }
                    }

                    if (performedAtLeastOneUpdate)
                    {
                        FinishPriceTableEntry updatedTableEntry = finishPriceTableRepository.update(tableEntryToUpdate);

                        if (updatedTableEntry == null)
                        {
                            throw new InvalidOperationException(UPDATE_NOT_SUCCESSFUL);
                        }

                        GetMaterialFinishPriceModelView updatedTableEntryModelView = new GetMaterialFinishPriceModelView();

                        updatedTableEntryModelView.id           = updatedTableEntry.Id;
                        updatedTableEntryModelView.finishId     = updatedTableEntry.entity.Id;
                        updatedTableEntryModelView.value        = updatedTableEntry.price.value;
                        updatedTableEntryModelView.currency     = defaultCurrency;
                        updatedTableEntryModelView.area         = defaultArea;
                        updatedTableEntryModelView.startingDate = LocalDateTimePattern.GeneralIso.Format(updatedTableEntry.timePeriod.startingDate);
                        updatedTableEntryModelView.endingDate   = LocalDateTimePattern.GeneralIso.Format(updatedTableEntry.timePeriod.endingDate);

                        return(updatedTableEntryModelView);
                    }
                }
            }
            throw new ResourceNotFoundException(FINISH_NOT_FOUND_OR_DOESNT_BELONG_TO_MATERIAL);
        }
Esempio n. 39
0
        /// <summary>
        /// Calculate the schedule working time between the specified dates and times
        /// </summary>
        /// <param name="from">Starting date and time</param>
        /// <param name="to">Ending date and time</param>
        /// <returns>Duration</returns>
        public Duration CalculateWorkingTime(LocalDateTime from, LocalDateTime to)
        {
            if (from.CompareTo(to) > 0)
            {
                string msg = string.Format(WorkSchedule.GetMessage("end.earlier.than.start"), to, from);
                throw new Exception(msg);
            }

            Duration sum = Duration.Zero;

            LocalDate thisDate = from.Date;
            LocalTime thisTime = from.TimeOfDay;
            LocalDate toDate   = to.Date;
            LocalTime toTime   = to.TimeOfDay;
            int       dayCount = Rotation.GetDayCount();

            // get the working shift from yesterday
            Shift lastShift = null;

            LocalDate     yesterday         = thisDate.PlusDays(-1);
            ShiftInstance yesterdayInstance = GetShiftInstanceForDay(yesterday);

            if (yesterdayInstance != null)
            {
                lastShift = yesterdayInstance.Shift;
            }

            // step through each day until done
            while (thisDate.CompareTo(toDate) < 1)
            {
                if (lastShift != null && lastShift.SpansMidnight())
                {
                    // check for days in the middle of the time period
                    bool lastDay = thisDate.CompareTo(toDate) == 0 ? true : false;

                    if (!lastDay || (lastDay && !toTime.Equals(LocalTime.Midnight)))
                    {
                        // add time after midnight in this day
                        int afterMidnightSecond = TimePeriod.SecondOfDay(lastShift.GetEnd());
                        int fromSecond          = TimePeriod.SecondOfDay(thisTime);

                        if (afterMidnightSecond > fromSecond)
                        {
                            Duration seconds = Duration.FromSeconds(afterMidnightSecond - fromSecond);
                            sum = sum.Plus(seconds);
                        }
                    }
                }

                // today's shift
                ShiftInstance instance = GetShiftInstanceForDay(thisDate);

                Duration duration;

                if (instance != null)
                {
                    lastShift = instance.Shift;
                    // check for last date
                    if (thisDate.CompareTo(toDate) == 0)
                    {
                        duration = lastShift.CalculateWorkingTime(thisTime, toTime, true);
                    }
                    else
                    {
                        duration = lastShift.CalculateWorkingTime(thisTime, LocalTime.MaxValue, true);
                    }
                    sum = sum.Plus(duration);
                }
                else
                {
                    lastShift = null;
                }

                int n = 1;
                if (GetDayInRotation(thisDate) == dayCount)
                {
                    // move ahead by the rotation count if possible
                    LocalDate rotationEndDate = thisDate.PlusDays(dayCount);

                    if (rotationEndDate.CompareTo(toDate) < 0)
                    {
                        n   = dayCount;
                        sum = sum.Plus(Rotation.GetWorkingTime());
                    }
                }

                // move ahead n days starting at midnight
                thisDate = thisDate.PlusDays(n);
                thisTime = LocalTime.Midnight;
            }             // end day loop

            return(sum);
        }
 protected override OffsetDateTime Unwrap(LocalDateTime property1Value, Offset property2Value) => new OffsetDateTime(property1Value, property2Value);
Esempio n. 41
0
 public async Task OnGet([FromQuery] int?year, [FromQuery] int?month)
 {
     if (year.HasValue && month.HasValue)
     {
         SetMonth(new YearMonth(year.Value, month.Value));
     }
     else
     {
         SetMonth(TzdbDateTimeZoneSource.Default.ForId("Asia/Tokyo").AtStrictly(LocalDateTime.FromDateTime(DateTime.UtcNow)).Date.ToYearMonth());
     }
     Appointments = await _service.SearchAppointmentsByYearMonthAsync(Month);
 }
Esempio n. 42
0
 private ZonedDateTime BuildZonedDateTime(ZoneInterval interval) =>
 new ZonedDateTime(LocalDateTime.WithOffset(interval.WallOffset), Zone);
        public static bool LocalDateTimeConverter(string name, LocalDateTime value, QueryValueConvertionType type, out string strValue)
        {
            strValue = value.ToString(NodaUtil.LocalDateTime.FullIsoPattern.PatternText, null);

            return(true);
        }
        public void ShouldCreateDateTimeWithDateTimeComponents()
        {
            var cypherDateTime = new LocalDateTime(1947, 12, 17, 23, 49, 54);

            cypherDateTime.ToDateTime().Should().Be(new DateTime(1947, 12, 17, 23, 49, 54));
        }
Esempio n. 45
0
 /// <summary>
 /// Override for efficiency: we know we'll always have an unambiguous mapping for any LocalDateTime.
 /// </summary>
 public override ZoneLocalMapping MapLocal(LocalDateTime localDateTime) =>
 new ZoneLocalMapping(this, localDateTime, interval, interval, 1);
        public void ShouldCreateDateTimeWithDateTimeComponentsWithNanoseconds()
        {
            var cypherDateTime = new LocalDateTime(1947, 12, 17, 23, 49, 54, 192794500);

            cypherDateTime.ToDateTime().Should().Be(new DateTime(1947, 12, 17, 23, 49, 54).AddTicks(1927945));
        }
Esempio n. 47
0
 public bool Contains(LocalDateTime LocalDateTime) => LocalDateTime >= start && LocalDateTime < end;
Esempio n. 48
0
        internal GeneralLedgerEntry(GeneralLedgerEntryIdentifier identifier,
                                    GeneralLedgerEntryNumber number, AccountingPeriod accountingPeriod, LocalDateTime createdOn) : this()
        {
            if (!accountingPeriod.Contains(createdOn.Date))
            {
                throw new GeneralLedgerEntryNotInPeriodException(number, createdOn, accountingPeriod);
            }

            Apply(new GeneralLedgerEntryCreated {
                GeneralLedgerEntryId = identifier.ToGuid(),
                Number    = number.ToString(),
                CreatedOn = Time.Format.LocalDateTime(createdOn),
                Period    = accountingPeriod.ToString()
            });
        }
Esempio n. 49
0
        public void InZoneStrictly_ThrowsWhenAmbiguous()
        {
            var local = new LocalDateTime(2009, 11, 1, 1, 30, 0);

            Assert.Throws <AmbiguousTimeException>(() => local.InZoneStrictly(Pacific));
        }
Esempio n. 50
0
 /// <summary>
 /// Gets last day of week
 /// </summary>
 /// <param name="ldt"></param>
 /// <returns></returns>
 public static LocalDateTime LastDayOfWeek(this LocalDateTime ldt) => ldt.FirstDayOfWeek().AddDays(6);
Esempio n. 51
0
        public void DefaultConstructor()
        {
            var actual = new LocalDateTime();

            Assert.AreEqual(new LocalDateTime(1, 1, 1, 0, 0), actual);
        }
Esempio n. 52
0
 private bool DayMatches(LocalDateTime aDate) => aDate.DayOfWeek == _dayIndex;
Esempio n. 53
0
        public void XmlSerialization_NonIso()
        {
            var value = new LocalDateTime(2013, 4, 12, 17, 53, 23, CalendarSystem.Julian);

            TestHelper.AssertXmlRoundtrip(value, "<value calendar=\"Julian\">2013-04-12T17:53:23</value>");
        }
Esempio n. 54
0
        public void Timestamp(LocalDateTime localDateTime)
        {
            using (var conn = OpenConnection())
            {
                var instant = localDateTime.InUtc().ToInstant();
                var minTimestampPostgres = Instant.FromUtc(-4713, 12, 31, 00, 00, 00);
                var maxTimestampPostgres = Instant.MaxValue;

                conn.ExecuteNonQuery("CREATE TEMP TABLE data (d1 TIMESTAMP, d2 TIMESTAMP, d3 TIMESTAMP, d4 TIMESTAMP, d5 TIMESTAMP, d6 TIMESTAMP, d7 TIMESTAMP)");

                using (var cmd = new NpgsqlCommand("INSERT INTO data VALUES (@p1, @p2, @p3, @p4, @p5, @p6, @p7)", conn))
                {
                    cmd.Parameters.Add(new NpgsqlParameter("p1", NpgsqlDbType.Timestamp)
                    {
                        Value = instant
                    });
                    cmd.Parameters.Add(new NpgsqlParameter("p2", DbType.DateTime)
                    {
                        Value = instant
                    });
                    cmd.Parameters.Add(new NpgsqlParameter("p3", DbType.DateTime2)
                    {
                        Value = instant
                    });
                    cmd.Parameters.Add(new NpgsqlParameter {
                        ParameterName = "p4", Value = instant
                    });
                    cmd.Parameters.Add(new NpgsqlParameter {
                        ParameterName = "p5", Value = localDateTime
                    });
                    cmd.Parameters.Add(new NpgsqlParameter {
                        ParameterName = "p6", Value = minTimestampPostgres
                    });
                    cmd.Parameters.Add(new NpgsqlParameter {
                        ParameterName = "p7", Value = maxTimestampPostgres
                    });
                    cmd.ExecuteNonQuery();
                }

                // Make sure the values inserted are the good ones, textually
                using (var cmd = new NpgsqlCommand("SELECT d1::TEXT, d2::TEXT, d3::TEXT, d4::TEXT, d5::TEXT FROM data", conn))
                    using (var reader = cmd.ExecuteReader())
                    {
                        reader.Read();
                        for (var i = 0; i < reader.FieldCount; i++)
                        {
                            Assert.That(reader.GetValue(i), Is.EqualTo(instant.ToString("yyyy'-'MM'-'dd' 'HH':'mm':'ss'.'FFFFFF", CultureInfo.InvariantCulture)));
                        }
                    }

                using (var cmd = new NpgsqlCommand("SELECT d6::TEXT, d7::TEXT FROM data", conn))
                    using (var reader = cmd.ExecuteReader())
                    {
                        reader.Read();
                        Assert.That(reader.GetValue(0), Is.EqualTo("4714-12-31 00:00:00 BC"));
                        Assert.That(reader.GetValue(1), Is.EqualTo(maxTimestampPostgres.ToString("yyyy'-'MM'-'dd' 'HH':'mm':'ss'.'FFFFFF", CultureInfo.InvariantCulture)));
                    }

                using (var cmd = new NpgsqlCommand("SELECT d1, d2, d3, d4, d5 FROM data", conn))
                    using (var reader = cmd.ExecuteReader())
                    {
                        reader.Read();

                        for (var i = 0; i < reader.FieldCount; i++)
                        {
                            Assert.That(reader.GetFieldType(i), Is.EqualTo(typeof(Instant)));
                            Assert.That(reader.GetFieldValue <Instant>(i), Is.EqualTo(instant));
                            Assert.That(reader.GetValue(i), Is.EqualTo(instant));
                            Assert.That(reader.GetFieldValue <LocalDateTime>(i), Is.EqualTo(localDateTime));
                            Assert.That(() => reader.GetFieldValue <ZonedDateTime>(i), Throws.TypeOf <InvalidCastException>());
                            Assert.That(() => reader.GetDateTime(i), Throws.TypeOf <InvalidCastException>());
                            Assert.That(() => reader.GetDate(i), Throws.TypeOf <InvalidCastException>());
                        }
                    }
            }
        }
Esempio n. 55
0
 internal InstantPatternParser(Instant templateValue)
 {
     localTemplateValue = templateValue.InUtc().LocalDateTime;
 }
Esempio n. 56
0
 public static string LocalDateTime(LocalDateTime value) => LocalDateTimePattern.Format(value);
Esempio n. 57
0
 public override bool Includes(LocalDateTime aDate) => DayMatches(aDate);
Esempio n. 58
0
        public void LocalDateTimeConverter_SerializeNonIso_Throws()
        {
            var localDateTime = new LocalDateTime(2012, 1, 2, 3, 4, 5, CalendarSystem.Coptic);

            Assert.Throws <ArgumentException>(() => this.AssertCsvSerialization(localDateTime, null, NodatimeConverters.LocalDateTimeConverter));
        }
Esempio n. 59
0
        internal static Personal ToPersonal(this Patient patient)
        {
            var personal = patient.ToThingBase <Personal>();
            var hasValue = false;

            var personalExtension = patient.GetExtension(HealthVaultExtensions.PatientPersonal);

            if (personalExtension != null)
            {
                personal.BloodType             = personalExtension.GetExtensionValue <CodeableConcept>(HealthVaultExtensions.PatientBloodType)?.ToCodableValue();
                personal.Ethnicity             = personalExtension.GetExtensionValue <CodeableConcept>(HealthVaultExtensions.PatientEthnicity)?.ToCodableValue();
                personal.HighestEducationLevel = personalExtension.GetExtensionValue <CodeableConcept>(HealthVaultExtensions.PatientHighestEducationLevel)?.ToCodableValue();
                personal.IsDisabled            = personalExtension.GetBoolExtension(HealthVaultExtensions.PatientIsDisabled);
                personal.MaritalStatus         = personalExtension.GetExtensionValue <CodeableConcept>(HealthVaultExtensions.PatientMaritalStatus)?.ToCodableValue();
                personal.IsVeteran             = personalExtension.GetBoolExtension(HealthVaultExtensions.PatientIsVeteran);
                personal.OrganDonor            = personalExtension.GetStringExtension(HealthVaultExtensions.PatientOrganDonor);
                personal.EmploymentStatus      = personalExtension.GetStringExtension(HealthVaultExtensions.PatientEmploymentStatus);
                personal.Religion             = personalExtension.GetExtensionValue <CodeableConcept>(HealthVaultExtensions.PatientReligion)?.ToCodableValue();
                personal.SocialSecurityNumber = patient.Identifier.FirstOrDefault(x => x.System == Constants.FhirExtensions.SSN)?.Value;

                if (personal.BloodType != null ||
                    personal.Ethnicity != null ||
                    personal.HighestEducationLevel != null ||
                    personal.IsDisabled != null ||
                    personal.MaritalStatus != null ||
                    personal.IsVeteran != null ||
                    !string.IsNullOrEmpty(personal.OrganDonor) ||
                    !string.IsNullOrEmpty(personal.EmploymentStatus) ||
                    personal.Religion != null ||
                    personal.SocialSecurityNumber != null)
                {
                    hasValue = true;
                }
            }

            if (patient.BirthDateElement != null)
            {
                hasValue           = true;
                personal.BirthDate = new HealthServiceDateTime(LocalDateTime.FromDateTime(patient.BirthDateElement.ToDateTime().Value))
                {
                    Time = patient.BirthDateElement.GetExtensionValue <Time>(HealthVaultExtensions.PatientBirthTime)?.ToAppoximateTime()
                };
            }

            if (patient.Deceased != null)
            {
                hasValue = true;
                switch (patient.Deceased)
                {
                case FhirBoolean b:
                    personal.IsDeceased = b.Value;
                    break;

                case FhirDateTime d:
                    personal.IsDeceased = true;
                    var dt = d.ToDateTimeOffset();
                    personal.DateOfDeath = new ApproximateDateTime(
                        new ApproximateDate(dt.Year, dt.Month, dt.Day),
                        new ApproximateTime(dt.Hour, dt.Minute, dt.Second, dt.Millisecond));
                    break;
                }
            }

            if (!patient.Name.IsNullOrEmpty())
            {
                hasValue = true;
                var patientName = patient.Name.First(); // Take the first name available
                personal.Name = patientName.ToHealthVault();
            }

            return(hasValue ? personal : null);
        }
Esempio n. 60
0
        public void Between_LocalDateTime_SameValue()
        {
            LocalDateTime start = new LocalDateTime(2014, 1, 1, 16, 0, 0);

            Assert.AreSame(Period.Zero, Period.Between(start, start));
        }