private IEventCentricTestSpecificationBuilder Scenario7(Fixture fixture,
                                                                CrabHouseNumberId crabHouseNumberId,
                                                                WkbGeometry geometry1,
                                                                WkbGeometry geometry2,
                                                                WkbGeometry geometry3,
                                                                WkbGeometry geometry4)
        {
            var addressId = new AddressId(crabHouseNumberId.CreateDeterministicId());

            var command = new ImportHouseNumberPositionFromCrab(
                new CrabAddressPositionId(4087928),
                crabHouseNumberId,
                geometry3,
                new CrabAddressNature("2"),
                Enum.Parse <CrabAddressPositionOrigin>("2"),
                new CrabLifetime(LocalDateTime.FromDateTime(new DateTime(1830, 1, 1)), null),
                new CrabTimestamp(Instant.FromDateTimeOffset(new DateTimeOffset(2015, 7, 30, 10, 57, 33, 920, TimeSpan.Zero))),
                new CrabOperator("13040:7405:DAERO"),
                CrabModification.Delete,
                Enum.Parse <CrabOrganisation>("1"));

            return(new AutoFixtureScenario(fixture)
                   .Given(Scenario6(fixture, crabHouseNumberId, geometry1, geometry2, geometry3, geometry4))
                   .When(command)
                   .Then(addressId,
                         new AddressWasPositioned(addressId, new AddressGeometry(GeometryMethod.DerivedFromObject, GeometrySpecification.BuildingUnit, GeometryHelpers.CreateEwkbFrom(geometry4))),
                         command.ToLegacyEvent()));
        }
Ejemplo n.º 2
0
        public static DateTime AsUtc(this IDateTime dateTime)
        {
            if (dateTime.IsUniversalTime)
            {
                return(DateTime.SpecifyKind(dateTime.Value, DateTimeKind.Utc));
            }
            if (!string.IsNullOrEmpty(dateTime.TZID))
            {
                var zone = DateTimeZoneProviders.Tzdb.GetZoneOrNull(dateTime.TZID);
                if (zone == null)
                {
                    var mappedTzid = TimeZoneMapper.WindowsToIanaOrNull(dateTime.TZID);
                    zone = mappedTzid != null
                        ? DateTimeZoneProviders.Tzdb.GetZoneOrNull(mappedTzid)
                        : BclDateTimeZone.ForSystemDefault();
                }

                if (zone != null)
                {
                    var localDateTime = LocalDateTime.FromDateTime(dateTime.Value);
                    var zonedDateTime = zone.AtLeniently(localDateTime);
                    var utcDateTime   = zonedDateTime.ToDateTimeUtc();
                    return(utcDateTime);
                }
            }

            // fallback
            return(DateTime.SpecifyKind(dateTime.Value, DateTimeKind.Local).ToUniversalTime());
        }
Ejemplo n.º 3
0
        public static ZonedDateTime FromTimeZoneToTimeZone(DateTime dateTime, DateTimeZone fromZone, DateTimeZone toZone)
        {
            var oldZone = LocalDateTime.FromDateTime(dateTime).InZoneLeniently(fromZone);
            var newZone = oldZone.WithZone(toZone);

            return(newZone);
        }
Ejemplo n.º 4
0
        async Task CheckEventNotifications()
        {
            var events = await EventDataService.GetEvents();

            foreach (var eventModel in events)
            {
                var eventNotifications = await EventNotificationDataService.GetEventNotificationsById(eventModel.Id);

                var timeElapsed = Period.Between(LocalDateTime.FromDateTime(eventModel.EventDate), LocalDateTime.FromDateTime(DateTime.Now));
                var months      = timeElapsed.Years * 12 + timeElapsed.Months;

                //check if months equals any of monthly anniversaries or is a yearly anniv
                if (hardCodedAnniversaries.Contains(months) || (months != 0 && months % 12 == 0))
                {
                    var hasBeenSent = eventNotifications.Where(x => x.MonthQuantifier == months);

                    //no notification has been sent
                    if (hasBeenSent.Count() < 1)
                    {
                        await _notificationManager.Send("Congratulations!", $"It has been {months} months for {eventModel.Name}!");

                        await EventNotificationDataService.AddEventNotification(new Models.EventNotification {
                            EventId = eventModel.Id, MonthQuantifier = months
                        });
                    }
                }
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TimeZoneOffsetProvider"/> class
        /// </summary>
        /// <param name="timeZone">The time zone to provide offsets for</param>
        /// <param name="utcStartTime">The start of the range of offsets</param>
        /// <param name="utcEndTime">The en of the range of offsets</param>
        public TimeZoneOffsetProvider(DateTimeZone timeZone, DateTime utcStartTime, DateTime utcEndTime)
        {
            _timeZone = timeZone;
            // pad the end so we get the correct zone interval
            utcEndTime += TimeSpan.FromDays(2 * 365);
            var start         = DateTimeZone.Utc.AtLeniently(LocalDateTime.FromDateTime(utcStartTime));
            var end           = DateTimeZone.Utc.AtLeniently(LocalDateTime.FromDateTime(utcEndTime));
            var zoneIntervals = _timeZone.GetZoneIntervals(start.ToInstant(), end.ToInstant()).ToList();

            // short circuit time zones with no discontinuities
            if (zoneIntervals.Count == 1 && zoneIntervals[0].Start == Instant.MinValue && zoneIntervals[0].End == Instant.MaxValue)
            {
                // end of discontinuities
                _discontinuities    = new Queue <long>();
                _nextDiscontinuity  = DateTime.MaxValue.Ticks;
                _currentOffsetTicks = _timeZone.GetUtcOffset(Instant.FromDateTimeUtc(DateTime.UtcNow)).Ticks;
            }
            else
            {
                // get the offset just before the next discontinuity to initialize
                _discontinuities    = new Queue <long>(zoneIntervals.Select(GetDateTimeUtcTicks));
                _nextDiscontinuity  = _discontinuities.Dequeue();
                _currentOffsetTicks = _timeZone.GetUtcOffset(Instant.FromDateTimeUtc(new DateTime(_nextDiscontinuity - 1, DateTimeKind.Utc))).Ticks;
            }
        }
Ejemplo n.º 6
0
        public bool InsertRehearsal(Rehearsal rehearsal)
        {
            // insert into rehearsal table// define a query
            string query = "INSERT INTO public.\"rehearsals\"(" +
                           " \"dtmStartDateTime\", \"dtmEndDateTime\", \"strLocation\", \"strNotes\", \"intEventID\")" +
                           " VALUES(@dtmStartDateTime, @dtmEndDateTime, @strLocation, @strNotes, @intEventID)" +
                           " RETURNING \"intRehearsalID\";";
            NpgsqlCommand cmd = new NpgsqlCommand(query, conn);

            cmd.Parameters.AddWithValue("dtmStartDateTime", LocalDateTime.FromDateTime(rehearsal.DtmStartDateTime));
            cmd.Parameters.AddWithValue("dtmEndDateTime", LocalDateTime.FromDateTime(rehearsal.DtmEndDateTime));
            cmd.Parameters.AddWithValue("strLocation", rehearsal.StrLocation);
            cmd.Parameters.AddWithValue("strNotes", rehearsal.StrNotes);
            cmd.Parameters.AddWithValue("intEventID", rehearsal.LstRehearsalParts.FirstOrDefault().Event.IntEventID);

            int intNewRehearsalID = (int)cmd.ExecuteScalar();

            bool status = false;

            // update each rehearsal part with the new rehearsal id
            foreach (RehearsalPart rp in rehearsal.LstRehearsalParts)
            {
                status = UpdateRehearsalPartWithRehearsal(rp, intNewRehearsalID);
            }

            return(status);
        }
Ejemplo n.º 7
0
        public MasterGameYear ToDomain(IEnumerable <MasterSubGame> subGames, EligibilityLevel eligibilityLevel, int year)
        {
            LocalDate?releaseDate = null;

            if (ReleaseDate.HasValue)
            {
                releaseDate = LocalDate.FromDateTime(ReleaseDate.Value);
            }

            LocalDate?sortableEstimatedReleaseDate = null;

            if (SortableEstimatedReleaseDate.HasValue)
            {
                sortableEstimatedReleaseDate = LocalDate.FromDateTime(SortableEstimatedReleaseDate.Value);
            }

            Instant?firstCriticScoreTimestamp = null;

            if (FirstCriticScoreTimestamp.HasValue)
            {
                firstCriticScoreTimestamp = Instant.FromDateTimeUtc(FirstCriticScoreTimestamp.Value);
            }

            var addedTimestamp      = LocalDateTime.FromDateTime(AddedTimestamp).InZoneStrictly(DateTimeZone.Utc).ToInstant();
            var eligibilitySettings = new EligibilitySettings(eligibilityLevel, YearlyInstallment, EarlyAccess, FreeToPlay, ReleasedInternationally, ExpansionPack, UnannouncedGame);

            var masterGame = new MasterGame(MasterGameID, GameName, EstimatedReleaseDate, sortableEstimatedReleaseDate, releaseDate,
                                            OpenCriticID, CriticScore, LocalDate.FromDateTime(MinimumReleaseDate), eligibilitySettings, subGames.ToList(), BoxartFileName, firstCriticScoreTimestamp,
                                            false, false, EligibilityChanged, addedTimestamp);

            return(new MasterGameYear(masterGame, year, PercentStandardGame, PercentCounterPick, EligiblePercentStandardGame, EligiblePercentCounterPick,
                                      NumberOfBids, TotalBidAmount, BidPercentile, AverageDraftPosition, AverageWinningBid, HypeFactor, DateAdjustedHypeFactor, LinearRegressionHypeFactor));
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            var localDateConverter =
                new ValueConverter <LocalDate, DateTime>(v =>
                                                         v.ToDateTimeUnspecified(),
                                                         v => LocalDate.FromDateTime(v));

            var localDateTimeConverter =
                new ValueConverter <LocalDateTime, DateTime>(v =>
                                                             v.ToDateTimeUnspecified(),
                                                             v => LocalDateTime.FromDateTime(v));

            var periodConverter =
                new ValueConverter <Period, TimeSpan>(v =>
                                                      v.ToDuration().ToTimeSpan(),
                                                      v => Period.FromTicks(v.Ticks));

            modelBuilder.Entity <AppointmentSlot>()
            .Property(e => e.From)
            .HasConversion(localDateTimeConverter);
            modelBuilder.Entity <AppointmentSlot>()
            .Property(e => e.Duration)
            .HasConversion(periodConverter);

            modelBuilder.Entity <Appointment>()
            .HasIndex(e => e.From);
            modelBuilder.Entity <Appointment>()
            .Property(e => e.From)
            .HasConversion(localDateTimeConverter);
            modelBuilder.Entity <Appointment>()
            .Property(e => e.Duration)
            .HasConversion(periodConverter);
        }
Ejemplo n.º 9
0
        public IActionResult CreateOrder(InMemoryOrder order)
        {
            order.Created = LocalDateTime.FromDateTime(DateTime.Now);
            var actionresult = CreatedAtAction("CreateOrder", dataAccess.InsertOrder(order.DatabaseOrderFactory(this.dataAccess)));

            return(actionresult);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Convert a given datetime from a timezone to another timezone
        /// </summary>
        /// <param name="datetime"></param>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <returns></returns>
        public static ZonedDateTime ConvertDateTimeToDifferentTimeZone(DateTime datetime, DateTimeZone from, DateTimeZone to)
        {
            var           fromLocal    = LocalDateTime.FromDateTime(datetime);
            ZonedDateTime fromDatetime = from.AtStrictly(fromLocal);

            return(fromDatetime.WithZone(to));
        }
Ejemplo n.º 11
0
        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            if (value is LocalDateTime ldt)
            {
                return(ldt);
            }
            if (value is LocalDate ld)
            {
                return(ld.AtMidnight());
            }
            if (value is DateTime d && d == d.Date)
            {
                return(LocalDate.FromDateTime(d));
            }
            if (value is string s)
            {
                var r = _pattern.WithCulture(culture ?? CultureInfo.InvariantCulture).Parse(s);
                if (r.Success)
                {
                    return(r.Value);
                }
                // little hack, not the finest, but should work
                if (DateTime.TryParse(s, out var dt))
                {
                    return(LocalDateTime.FromDateTime(dt));
                }
            }


            return(base.ConvertFrom(context, culture, value));
        }
        public void SetDates(DateTime start, DateTime end)
        {
            var ldt1 = LocalDateTime.FromDateTime(start);
            var ldt2 = LocalDateTime.FromDateTime(end);

            _period = Period.Between(ldt1, ldt2);
        }
Ejemplo n.º 13
0
        //VssConnection vss
        public IEnumerable <CheckIn> GetHistory(string path)
        {
            var z = _vcServer.QueryHistory(path, RecursionType.Full);

            foreach (var changeset in z)
            {
                if (changeset != null && changeset.Comment != null)
                {
                    if (changeset.Comment.Length > 250)
                    {
                        changeset.Comment = changeset.Comment.Substring(0, 250);
                    }

                    var name = changeset.CommitterDisplayName;
                    if (name.Contains(" OLD"))
                    {
                        name = name.Replace(" OLD", "");
                    }

                    yield return(new CheckIn
                    {
                        Id = changeset.ChangesetId,
                        comment = changeset.Comment,
                        date = LocalDateTime.FromDateTime(changeset.CreationDate),
                        committerName = name,
                        committerEmail = GetUserEmail(changeset.Committer, changeset.CommitterDisplayName)
                    });
                }
            }
        }
        private IEventCentricTestSpecificationBuilder Scenario1(Fixture fixture,
                                                                CrabHouseNumberId crabHouseNumberId,
                                                                WkbGeometry geometry)
        {
            var addressId = new AddressId(crabHouseNumberId.CreateDeterministicId());

            var addressWasRegistered = new AddressWasRegistered(
                addressId,
                fixture.Create <StreetNameId>(),
                fixture.Create <HouseNumber>());

            ((ISetProvenance)addressWasRegistered).SetProvenance(fixture.Create <Provenance>());

            var command = new ImportHouseNumberPositionFromCrab(
                new CrabAddressPositionId(1),
                crabHouseNumberId,
                geometry,
                new CrabAddressNature("2"),
                Enum.Parse <CrabAddressPositionOrigin>("10"),
                new CrabLifetime(LocalDateTime.FromDateTime(new DateTime(1830, 1, 1)), null),
                new CrabTimestamp(Instant.FromDateTimeOffset(new DateTimeOffset(2011, 4, 29, 14, 50, 10, 483, TimeSpan.Zero))),
                new CrabOperator("VLM\\thijsge"),
                CrabModification.Insert,
                Enum.Parse <CrabOrganisation>("5"));

            return(new Scenario()
                   .Given(addressId, addressWasRegistered)
                   .When(command)
                   .Then(addressId,
                         new AddressWasPositioned(addressId, new AddressGeometry(GeometryMethod.DerivedFromObject, GeometrySpecification.BuildingUnit, GeometryHelpers.CreateEwkbFrom(geometry))),
                         command.ToLegacyEvent()));
        }
Ejemplo n.º 15
0
        public bool InsertCallboard(Callboard callboard)
        {
            // define a query
            string query = "INSERT INTO public.callboard(" +
                           "\"strSubject\", \"strNote\", \"dtmDateTime\", \"intPostedByUserID\", \"intEventID\")" +
                           " VALUES(@strSubject, @strNote, @dtmDateTime, @intPostedByUserID, @intEventID);";
            NpgsqlCommand cmd = new NpgsqlCommand(query, conn);

            if (callboard.StrNote == null)
            {
                cmd.Parameters.AddWithValue("strNote", DBNull.Value);
            }
            else
            {
                cmd.Parameters.AddWithValue("strNote", callboard.StrNote);
            }

            cmd.Parameters.AddWithValue("strSubject", callboard.StrSubject);
            cmd.Parameters.AddWithValue("strNote", callboard.StrNote);
            cmd.Parameters.AddWithValue("dtmDateTime", LocalDateTime.FromDateTime(DateTime.Now));
            cmd.Parameters.AddWithValue("intPostedByUserID", Globals.LOGGED_IN_USER.IntUserID);
            cmd.Parameters.AddWithValue("intEventID", callboard.Event.IntEventID);

            int result = cmd.ExecuteNonQuery();

            if (result == 1)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 16
0
        public MasterGame ToDomain(IEnumerable <MasterSubGame> subGames, EligibilityLevel eligibilityLevel)
        {
            LocalDate?releaseDate = null;

            if (ReleaseDate.HasValue)
            {
                releaseDate = LocalDate.FromDateTime(ReleaseDate.Value);
            }

            LocalDate?sortableEstimatedReleaseDate = null;

            if (SortableEstimatedReleaseDate.HasValue)
            {
                sortableEstimatedReleaseDate = LocalDate.FromDateTime(SortableEstimatedReleaseDate.Value);
            }

            Instant?firstCriticScoreTimestamp = null;

            if (FirstCriticScoreTimestamp.HasValue)
            {
                firstCriticScoreTimestamp = Instant.FromDateTimeUtc(FirstCriticScoreTimestamp.Value);
            }

            var addedTimestamp      = LocalDateTime.FromDateTime(AddedTimestamp).InZoneStrictly(DateTimeZone.Utc).ToInstant();
            var eligibilitySettings = new EligibilitySettings(eligibilityLevel, YearlyInstallment, EarlyAccess, FreeToPlay, ReleasedInternationally, ExpansionPack, UnannouncedGame);

            return(new MasterGame(MasterGameID, GameName, EstimatedReleaseDate, sortableEstimatedReleaseDate, releaseDate, OpenCriticID, CriticScore, LocalDate.FromDateTime(MinimumReleaseDate),
                                  eligibilitySettings, subGames.ToList(), BoxartFileName, firstCriticScoreTimestamp, DoNotRefreshDate, DoNotRefreshAnything, EligibilityChanged, addedTimestamp));
        }
Ejemplo n.º 17
0
        public bool InsertTask(Task task)
        {
            // define a query
            string query = "INSERT INTO public.tasks(" +
                           "\"dtmDue\", \"strName\", \"strAttachment\", \"intAssignedToUserID\", \"intAssignedByUserID\", \"intEventID\", \"ysnIsFinished\")" +
                           " VALUES(@dtmDue, @strName, @strAttachment, @intAssignedToUserID, @intAssignedByUserID, @intEventID, false); ";
            NpgsqlCommand cmd = new NpgsqlCommand(query, conn);

            cmd.Parameters.AddWithValue("dtmDue", LocalDateTime.FromDateTime(task.DtmDue));
            cmd.Parameters.AddWithValue("strName", task.StrName);
            cmd.Parameters.AddWithValue("strAttachment", task.StrAttachment);
            cmd.Parameters.AddWithValue("intAssignedToUserID", task.UserAssignedTo.IntUserID);
            cmd.Parameters.AddWithValue("intAssignedByUserID", task.UserAssignedBy.IntUserID);
            cmd.Parameters.AddWithValue("intEventID", task.Event.IntEventID);

            int result = cmd.ExecuteNonQuery();

            if (result == 1)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 18
0
        public FantasyCriticUser ToDomain()
        {
            Instant           instant = LocalDateTime.FromDateTime(LastChangedCredentials).InZoneStrictly(DateTimeZone.Utc).ToInstant();
            FantasyCriticUser domain  = new FantasyCriticUser(UserID, UserName, NormalizedUserName, EmailAddress, NormalizedUserName, EmailConfirmed, SecurityStamp, PasswordHash, instant);

            return(domain);
        }
Ejemplo n.º 19
0
                public void CreateNewExport_ExportsNew()
                {
                    var mockHealth      = new Mock <IHealthStore>();
                    var mockFileManager = new Mock <IFileManager>();

                    var mockShare = new Mock <IShare>();

                    mockFileManager
                    .Setup(x => x.GetLatestExportFile())
                    .Returns(Some((new FileInfo("latest.xlsx"), LocalDateTime.FromDateTime(DateTime.Now), Output.XlsxContentType)));
                    mockFileManager
                    .Setup(x => x.GetNewFileName())
                    .Returns(new FileInfo("newFile.xlsx"));

                    var sut = GetSut(
                        fileManager: mockFileManager.Object,
                        healthStore: mockHealth.Object,
                        actionPresenter: new ShimActionPresenter(actions =>
                                                                 actions.Last().ToTake()), // execute the "create new" option,
                        share: mockShare.Object);

                    sut.Exporter.Command.Execute(null);

                    mockShare.Verify(s => s.RequestAsync(It.Is((ShareFileRequest r) =>
                                                               r.File.FullPath.EndsWith("newFile.xlsx"))));
                    mockHealth.Verify(h => h.GetHealthRecordsAsync(It.IsAny <DateInterval>()));
                }
Ejemplo n.º 20
0
        /// <summary>
        /// Converts local datetime to interval value basing on interval (db value)
        /// </summary>
        public static int ToIntervalValue(this DateTime localDateTime, IntervalEnum interval)
        {
            var epochStart = new LocalDateTime(2010, 01, 01, 0, 0, 0, 0); // Jan 1, 2010, a Friday
            var epochEnd   = LocalDateTime.FromDateTime(localDateTime);

            switch (interval)
            {
            case IntervalEnum.Day:
            case IntervalEnum.Custom:
                return((int)Period.Between(epochStart, epochEnd, PeriodUnits.Days).Days);

            case IntervalEnum.Week:
                return(((int)Period.Between(epochStart, epochEnd, PeriodUnits.Days).Days + 5) / 7);

            case IntervalEnum.Month:
                return((int)Period.Between(epochStart, epochEnd, PeriodUnits.Months).Months);

            case IntervalEnum.Year:
                return((int)Period.Between(epochStart, epochEnd, PeriodUnits.Years).Years);

            case IntervalEnum.AllTime:
                return(0);

            default:
                throw new NotSupportedException();
            }
        }
        public static int MonthDifference(this DateTime leftValue, DateTime rightValue)
        {
            int monthDiff = (int)Math.Abs(Period.Between(LocalDateTime.FromDateTime(leftValue), LocalDateTime.FromDateTime(rightValue)).Months);
            int yearDiff  = (int)Math.Abs(Period.Between(LocalDateTime.FromDateTime(leftValue), LocalDateTime.FromDateTime(rightValue)).Years);

            return(monthDiff + 12 * yearDiff);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Returns true if the entry is in the categoryName specified.
        /// </summary>
        /// <param name="entry">The entry to check for category</param>
        /// <param name="timeZone">The time zone.</param>
        /// <param name="dateTime">The latest date and time the entry can occur.</param>
        /// <returns>
        /// A value of true indicates the entry is in the category specified or, if the categoryName
        /// is null or empty, return true if the entry is assigned no categories
        /// </returns>
        public static bool OccursBefore(Entry entry, DateTimeZone timeZone, DateTime dateTime)
        {
            var entryCreated = timeZone.AtStrictly(LocalDateTime.FromDateTime(entry.CreatedUtc)).LocalDateTime;
            var date         = LocalDateTime.FromDateTime(dateTime);

            return(entryCreated <= date);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Convert date with local time to UTC
        /// </summary>
        /// <param name="dateInZone">Date in zone</param>
        /// <returns></returns>
        public static DateTime Convert(this DateTime dateInZone)
        {
            DateTimeZone timeZone = DateTimeZoneProviders.Bcl.GetSystemDefault();
            DateTime     utcTime  = LocalDateTime.FromDateTime(dateInZone).InZoneStrictly(timeZone).ToDateTimeUtc();

            return(utcTime);
        }
Ejemplo n.º 24
0
        [Test, Timeout(300000)] // Can take a long time under NCrunch.
        public void BclThroughHistory_Scriptural()
        {
            Calendar bcl  = new HebrewCalendar();
            var      noda = CalendarSystem.HebrewScriptural;

            // The min supported date/time starts part way through the year
            var minYear = bcl.GetYear(bcl.MinSupportedDateTime) + 1;
            // The max supported date/time ends part way through the year
            var maxYear = bcl.GetYear(bcl.MaxSupportedDateTime) - 1;

            // Can't use BclEquivalenceHelper for this one, because of the month conversions.
            for (int year = minYear; year <= maxYear; year++)
            {
                int months = bcl.GetMonthsInYear(year);
                Assert.AreEqual(months, noda.GetMonthsInYear(year));
                for (int civilMonth = 1; civilMonth <= months; civilMonth++)
                {
                    int scripturalMonth = HebrewMonthConverter.CivilToScriptural(year, civilMonth);
                    Assert.AreEqual(bcl.GetDaysInMonth(year, civilMonth), noda.GetDaysInMonth(year, scripturalMonth),
                                    "Year: {0}; Month: {1} (civil)", year, civilMonth);
                    for (int day = 1; day < bcl.GetDaysInMonth(year, civilMonth); day++)
                    {
                        DateTime  bclDate  = new DateTime(year, civilMonth, day, bcl);
                        LocalDate nodaDate = new LocalDate(year, scripturalMonth, day, noda);
                        Assert.AreEqual(bclDate, nodaDate.AtMidnight().ToDateTimeUnspecified(), "{0}-{1}-{2}", year, scripturalMonth, day);
                        Assert.AreEqual(nodaDate, LocalDateTime.FromDateTime(bclDate, noda).Date);
                        Assert.AreEqual(year, nodaDate.Year);
                        Assert.AreEqual(scripturalMonth, nodaDate.Month);
                        Assert.AreEqual(day, nodaDate.Day);
                    }
                }
            }
        }
Ejemplo n.º 25
0
        public async Task <ActionResult <IsItCabanaConTimeYetResponse> > IsItCabanaConTimeYet()
        {
            var query    = new IsItCabanaConTimeYetQuery(LocalDateTime.FromDateTime(DateTime.Now));
            var response = await _mediator.Send(query);

            return(Ok(response));
        }
Ejemplo n.º 26
0
 /// <summary>
 /// Converts the DateTime from Local to the UTC equivalent.
 /// </summary>
 /// <param name="dateToParse">The Local DateTime object to parse</param>
 /// <returns>A DateTime in a UTC equivalent</returns>
 public DateTime LocalToUtcDateTime(DateTime dateToParse)
 {
     return(LocalDateTime.FromDateTime(dateToParse)
            .InZoneLeniently(_dateTimeZone)
            .ToInstant()
            .ToDateTimeUtc());
 }
Ejemplo n.º 27
0
            // Converts a TimeZoneInfo "TransitionTime" to a "ZoneYearOffset" - the two correspond pretty closely.
            private static ZoneYearOffset ConvertTransition(TimeZoneInfo.TransitionTime transitionTime)
            {
                // Used for both fixed and non-fixed transitions.
                LocalTime timeOfDay = LocalDateTime.FromDateTime(transitionTime.TimeOfDay).TimeOfDay;

                // Easy case - fixed day of the month.
                if (transitionTime.IsFixedDateRule)
                {
                    return(new ZoneYearOffset(TransitionMode.Wall, transitionTime.Month, transitionTime.Day, 0, false, timeOfDay));
                }

                // Floating: 1st Sunday in March etc.
                int  dayOfWeek = (int)BclConversions.ToIsoDayOfWeek(transitionTime.DayOfWeek);
                int  dayOfMonth;
                bool advance;

                // "Last"
                if (transitionTime.Week == 5)
                {
                    advance    = false;
                    dayOfMonth = -1;
                }
                else
                {
                    advance = true;
                    // Week 1 corresponds to ">=1"
                    // Week 2 corresponds to ">=8" etc
                    dayOfMonth = (transitionTime.Week * 7) - 6;
                }
                return(new ZoneYearOffset(TransitionMode.Wall, transitionTime.Month, dayOfMonth, dayOfWeek, advance, timeOfDay));
            }
Ejemplo n.º 28
0
        public DateTime ConvertToUtc(
            DateTime localDateTime,
            string timeZoneId,
            ZoneLocalMappingResolver resolver = null
            )
        {
            if (localDateTime.Kind == DateTimeKind.Utc)
            {
                return(localDateTime);
            }

            if (resolver == null)
            {
                resolver = Resolvers.LenientResolver;
            }
            var timeZone = tzSource.GetZoneOrNull(timeZoneId);

            if (timeZone == null)
            {
                if (log != null)
                {
                    log.LogWarning("failed to find timezone for " + timeZoneId);
                }
                return(localDateTime);
            }

            var local = LocalDateTime.FromDateTime(localDateTime);
            var zoned = timeZone.ResolveLocal(local, resolver);

            return(zoned.ToDateTimeUtc());
        }
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null || value.GetType() != typeof(DateTime))
            {
                return(DateTime.MinValue);
            }

            // If should be set to DateTimeKind.Unspecified in Convert
            if (((DateTime)value).Kind != DateTimeKind.Unspecified)
            {
                return(value);
            }

            if (parameter == null || parameter.GetType() != typeof(string) || !DateTimeZoneProviders.Tzdb.Ids.Contains((string)parameter))
            {
                return(value);
            }

            var localDateTime = LocalDateTime.FromDateTime((DateTime)value);
            var timeZone      = DateTimeZoneProviders.Tzdb[(string)parameter];

            var zonedDbDateTime = timeZone.AtLeniently(localDateTime);

            return(zonedDbDateTime.ToDateTimeUtc());
        }
        private IEventCentricTestSpecificationBuilder Scenario6(Fixture fixture,
                                                                CrabHouseNumberId crabHouseNumberId,
                                                                WkbGeometry geometry1,
                                                                WkbGeometry geometry2,
                                                                WkbGeometry geometry3,
                                                                WkbGeometry geometry4)
        {
            var addressId = new AddressId(crabHouseNumberId.CreateDeterministicId());

            var command = new ImportHouseNumberPositionFromCrab(
                new CrabAddressPositionId(5790888),
                crabHouseNumberId,
                geometry4,
                new CrabAddressNature("2"),
                Enum.Parse <CrabAddressPositionOrigin>("10"),
                new CrabLifetime(LocalDateTime.FromDateTime(new DateTime(1830, 1, 1)), null),
                new CrabTimestamp(Instant.FromDateTimeOffset(new DateTimeOffset(2015, 7, 30, 10, 57, 33, 273, TimeSpan.Zero))),
                new CrabOperator("13040:7405:DAERO"),
                CrabModification.Insert,
                Enum.Parse <CrabOrganisation>("5"));

            return(new AutoFixtureScenario(fixture)
                   .Given(Scenario5(fixture, crabHouseNumberId, geometry1, geometry2, geometry3))
                   .When(command)
                   .Then(addressId,
                         command.ToLegacyEvent()));
        }