private void Can_Use_NodaTime_ZonedDateTime_In_Document(ZonedDateTime zdt) { using (var documentStore = NewDocumentStore()) { documentStore.ConfigureForNodaTime(); using (var session = documentStore.OpenSession()) { session.Store(new Foo { Id = "foos/1", ZonedDateTime = zdt }); session.SaveChanges(); } using (var session = documentStore.OpenSession()) { var foo = session.Load <Foo>("foos/1"); Assert.Equal(zdt, foo.ZonedDateTime); } var json = documentStore.DatabaseCommands.Get("foos/1").DataAsJson; Debug.WriteLine(json.ToString(Formatting.Indented)); var expectedDateTime = zdt.ToDateTimeOffset().ToString("o"); var expectedZone = zdt.Zone.Id; Assert.Equal(expectedDateTime, json["ZonedDateTime"].Value <string>("OffsetDateTime")); Assert.Equal(expectedZone, json["ZonedDateTime"].Value <string>("Zone")); } }
public void ShouldThrowOnTruncation(int nanosecond) { var dateTime = new ZonedDateTime(1, 1, 1, 0, 0, 0, nanosecond, Zone.Of("Europe/London")); var ex = Record.Exception(() => dateTime.ToDateTimeOffset()); ex.Should().NotBeNull().And.BeOfType <ValueTruncationException>(); }
public void ShouldThrowOnOverflow(int year) { var dateTime = new ZonedDateTime(year, 1, 1, 0, 0, 0, 0, Zone.Of("Europe/London")); var ex = Record.Exception(() => dateTime.ToDateTimeOffset()); ex.Should().NotBeNull().And.BeOfType <ValueOverflowException>(); }
public void ShouldConvertToDateTimeOffset() { var dateTime = new DateTimeOffset(1947, 12, 17, 23, 49, 54, 120, TimeSpan.FromSeconds(1500)); var cypherDateTime = new ZonedDateTime(dateTime); cypherDateTime.ToDateTimeOffset().Should().Be(dateTime); }
public void ToDateTimeOffset() { ZonedDateTime zoned = SampleZone.AtStrictly(new LocalDateTime(2011, 3, 5, 1, 0, 0)); DateTimeOffset expected = new DateTimeOffset(2011, 3, 5, 1, 0, 0, TimeSpan.FromHours(3)); DateTimeOffset actual = zoned.ToDateTimeOffset(); Assert.AreEqual(expected, actual); }
public static RavenJObject Resolve(ZonedDateTime value) { return(new RavenJObject { { "OffsetDateTime", value.ToDateTimeOffset() }, { "Zone", value.Zone.Id } }); }
static DateTimeOffset LocalTimeToUtc(string localDate) { var pattern = LocalDateTimePattern.CreateWithInvariantCulture("dd/MM/yyyy"); LocalDateTime ldt = pattern.Parse(localDate).Value; ZonedDateTime zdt = ldt.InZoneLeniently(DateTimeZoneProviders.Tzdb["Australia/Sydney"]); Instant instant = zdt.ToInstant(); ZonedDateTime utc = instant.InUtc(); return(utc.ToDateTimeOffset()); }
public void Can_RoundTrip_A_ZonedDateTime_To_DateTimeOffset_And_Back() { var systemDateTimeZone = DateTimeZoneProviders.Tzdb.GetSystemDefault(); Instant now = TestClock.Now; var zonedDateTimeNow = new ZonedDateTime(now, systemDateTimeZone); var dateTimeOffsetNow = zonedDateTimeNow.ToDateTimeOffset(); var zondedDateTimeRoundTripped = dateTimeOffsetNow.ToZonedDateTime(systemDateTimeZone); Assert.That(zonedDateTimeNow, Is.EqualTo(zondedDateTimeRoundTripped)); }
public void ToDateTimeOffset_JulianCalendar() { // Non-Gregorian calendar systems are handled by converting to the same // date, just like the DateTime constructor does. ZonedDateTime zoned = SampleZone.AtStrictly(new LocalDateTime(2011, 3, 5, 1, 0, 0, CalendarSystem.Julian)); DateTimeOffset expected = new DateTimeOffset(2011, 3, 5, 1, 0, 0, 0, new JulianCalendar(), TimeSpan.FromHours(3)); DateTimeOffset actual = zoned.ToDateTimeOffset(); Assert.AreEqual(expected, actual); }
/// <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)); } ZonedDateTime zonedDateTime = (ZonedDateTime)value; if (destinationType == typeof(string)) { // ReSharper disable PossibleNullReferenceException return(ZonedDateTimePattern.ExtendedFormatOnlyIsoPattern .WithZoneProvider(TimeHelpers.DateTimeZoneProvider) .Format(zonedDateTime)); } // ReSharper restore PossibleNullReferenceException if (destinationType == typeof(DateTime)) { return(zonedDateTime.ToDateTimeUtc()); } if (destinationType == typeof(DateTimeOffset)) { return(zonedDateTime.ToDateTimeOffset()); } if (destinationType == typeof(Instant)) { return(zonedDateTime.ToInstant()); } if (destinationType == typeof(LocalDateTime)) { return(zonedDateTime.LocalDateTime); } if (destinationType == typeof(OffsetDateTime)) { return(zonedDateTime.ToOffsetDateTime()); } return(base.ConvertTo(context, culture, value, destinationType)); }
public async Task <Guid> CreateNewWorkout(CreateViewModel model, string userId) { ZonedDateTime zonedTime = GetZonedTime(model.StartDateTime.Value, model.TimeZoneName); var workoutId = Guid.NewGuid(); await _mediator.Send( new StartWorkout( workoutId, userId, zonedTime.ToDateTimeOffset())); return(workoutId); }
public async Task <string> UpdateCalendarTimezoneAsync(ulong calendarId, string newTimezone) { var tz = DateTimeZoneProviders.Tzdb.GetZoneOrNull(newTimezone); if (tz == null) { throw new InvalidTimeZoneException("Invalid TZ timezone"); } Calendar calendar; using (var db = _contextFactory.CreateDbContext()) { calendar = await db.Calendars .Include(c => c.Events) .FirstOrDefaultAsync(c => c.Id == calendarId); if (calendar == null || string.IsNullOrEmpty(calendar.Timezone)) { throw new CalendarNotFoundException(); } var oldTz = DateTimeZoneProviders.Tzdb[calendar.Timezone]; var earliestEvent = calendar.Events.OrderBy(e => e.StartTimestamp).FirstOrDefault(); if (earliestEvent != null) { Instant instant = Instant.FromDateTimeOffset(earliestEvent.StartTimestamp); LocalDateTime dt = new ZonedDateTime(instant, oldTz).LocalDateTime; ZonedDateTime zdt = tz.AtStrictly(dt); if (zdt.ToInstant().ToDateTimeOffset() < SystemClock.Instance.GetCurrentInstant().ToDateTimeOffset()) { throw new ExistingEventInNewTimezonePastException(); } } calendar.Timezone = newTimezone; foreach (var evt in calendar.Events) { Instant startInstant = Instant.FromDateTimeOffset(evt.StartTimestamp); Instant endInstant = Instant.FromDateTimeOffset(evt.EndTimestamp); LocalDateTime startDt = new ZonedDateTime(startInstant, oldTz).LocalDateTime; LocalDateTime endDt = new ZonedDateTime(endInstant, oldTz).LocalDateTime; ZonedDateTime startZdt = tz.AtStrictly(startDt); ZonedDateTime endZdt = tz.AtStrictly(endDt); evt.StartTimestamp = startZdt.ToDateTimeOffset(); evt.EndTimestamp = endZdt.ToDateTimeOffset(); } await db.SaveChangesAsync(); } return(calendar.Timezone); }
public static List <ForecastHourly> GetHourlyWeatherOverPeriod(SimpleTime start, SimpleTime end, double lat, double lng) { LocalDateTime begin = new LocalDateTime(start.Year, start.Month, start.Day, 0, 0); LocalDateTime stop = new LocalDateTime(end.Year, end.Month, end.Day, 0, 0); Period period = Period.Between(begin, stop, PeriodUnits.Days); List <ForecastHourly> hourlyData = new List <ForecastHourly>(); for (int i = 0; i <= period.Days; i++) { LocalDateTime localtime = begin.PlusDays(i); string timezone = "America/Toronto"; DateTimeZone tz = DateTimeZoneProviders.Tzdb[timezone]; ZonedDateTime zt = tz.AtLeniently(localtime); var tz_offset = zt.ToDateTimeOffset(); Task.Run(async() => { var client = new ForecastApi(API_KEY); Forecast result = await client.GetTimeMachineWeatherAsync(lat, lng, tz_offset); var hourly = result.Hourly.Hours; for (int h = 0; h < hourly.Count(); h++) { ForecastHourly store_hourly = new ForecastHourly(); store_hourly.ApparentTemperature = hourly[h].ApparentTemperature; store_hourly.CloudCover = hourly[h].CloudCover; store_hourly.DewPoint = hourly[h].DewPoint; store_hourly.Humidity = hourly[h].Humidity; store_hourly.Icon = hourly[h].Icon; store_hourly.Ozone = hourly[h].Ozone; store_hourly.PrecipitationIntensity = hourly[h].PrecipitationIntensity; store_hourly.PrecipitationProbability = hourly[h].PrecipitationProbability; store_hourly.Pressure = hourly[h].Pressure; store_hourly.Summary = hourly[h].Summary; store_hourly.Temperature = hourly[h].Temperature; store_hourly.Time = hourly[h].Time; //Instant instant = Instant.FromDateTimeUtc(hourly[h].Time.UtcDateTime); //don't need this, already defined above store_hourly.LocalTime = zt.LocalDateTime; store_hourly.Visibility = hourly[h].Visibility; store_hourly.WindBearing = hourly[h].WindBearing; store_hourly.WindSpeed = hourly[h].WindSpeed; hourlyData.Add(store_hourly); } }).Wait(); } return(hourlyData); }
/// <summary> /// Called when each request is intercepted and has not gone to the server yet. /// </summary> internal ProxyNextAction OnBeforeRequest(GoproxyWrapper.Session args) { ProxyNextAction nextAction = ProxyNextAction.AllowAndIgnoreContent; int trackId = 0; lock (trackIdLock) { trackId = nextTrackId++; } // Don't allow filtering if our user has been denied access and they // have not logged back in. if (m_ipcServer != null && m_ipcServer.WaitingForAuth) { return(ProxyNextAction.AllowAndIgnoreContentAndResponse); } try { ZonedDateTime date = m_timeDetection.GetRealTime(); TimeRestrictionModel todayRestriction = null; if (m_policyConfiguration != null && m_policyConfiguration.TimeRestrictions != null && date != null) { todayRestriction = m_policyConfiguration.TimeRestrictions[(int)date.ToDateTimeOffset().DayOfWeek]; } string urlString = args.Request.Url; Uri url = new Uri(urlString); Uri serviceProviderPath = new Uri(CompileSecrets.ServiceProviderApiPath); if (url.Host == serviceProviderPath.Host) { return(ProxyNextAction.AllowAndIgnoreContentAndResponse); } else if (todayRestriction != null && todayRestriction.RestrictionsEnabled && !m_timeDetection.IsDateTimeAllowed(date, todayRestriction)) { sendBlockResponse(args, urlString, null, BlockType.TimeRestriction); return(ProxyNextAction.DropConnection); } } catch (Exception e) { LoggerUtil.RecursivelyLogException(m_logger, e); } return(nextAction); }
public void Can_Query_By_MoreThan_ZonedDateTime_Stored_As_DateTimeOffset() { var timeZone = DateTimeZoneProviders.Tzdb.GetSystemDefault(); Instant startInstant = TestClock.Now.Plus(Duration.FromHours(24)); ZonedDateTime startZonedDateTime = startInstant.InZone(timeZone); ZonedDateTime finishZonedDateTime = startZonedDateTime.Plus(Duration.FromHours(1)); var testEvent = new ZonedDateTimeTestEntity { Description = "Can_Query_By_LessThan_ZonedDateTime_Stored_As_DateTimeOffset", StartZonedDateTime = startZonedDateTime, FinishZonedDateTime = finishZonedDateTime }; using (ISession session = SessionFactory.OpenSession()) using (ITransaction transaction = session.BeginTransaction()) { session.Save(testEvent); transaction.Commit(); } ZonedDateTime beforeStart = startZonedDateTime.Minus(Duration.FromMinutes(1)); using (ISession session = SessionFactory.OpenSession()) using (ITransaction transaction = session.BeginTransaction()) { var query = session.Query <ZonedDateTimeTestEntity>() .Where(x => x.Id == testEvent.Id && x.StartZonedDateTime.ToDateTimeOffset() > beforeStart.ToDateTimeOffset()); var retrievedEvent = query.SingleOrDefault(); transaction.Commit(); Assert.That(testEvent, Is.Not.Null); Assert.That(testEvent, Is.EqualTo(retrievedEvent)); } using (ISession session = SessionFactory.OpenSession()) using (ITransaction transaction = session.BeginTransaction()) { var query = session.Query <ZonedDateTimeTestEntity>() .Where(x => x.Id == testEvent.Id && x.StartZonedDateTime.ToDateTimeOffset() > beforeStart.ToDateTimeOffset() && x.FinishZonedDateTime.Value.ToDateTimeOffset() >= finishZonedDateTime.ToDateTimeOffset()); var retrievedEvent = query.SingleOrDefault(); transaction.Commit(); Assert.That(testEvent, Is.Not.Null); Assert.That(testEvent, Is.EqualTo(retrievedEvent)); } }
public void Can_RoundTrip_A_ZonedDateTime_To_DateTimeOffset_Using_Persistence() { var systemDateTimeZone = DateTimeZoneProviders.Tzdb.GetSystemDefault(); Instant now = TestClock.Now; var zonedDateTimeStart = new ZonedDateTime(now, systemDateTimeZone); var zonedDateTimeFinish = zonedDateTimeStart.Plus(Duration.FromMinutes(60)); var testLocation = new LocationTestEntity { Description = "Can_RoundTrip_A_ZonedDateTime_To_DateTimeOffset_Using_Persistence", LocationDateTimeZone = systemDateTimeZone }; var testEvent = new DateTimeOffsetTestEntity { Description = "Can_RoundTrip_A_ZonedDateTime_To_DateTimeOffset_Using_Persistence", EventLocation = testLocation, StartDateTimeOffset = zonedDateTimeStart.ToDateTimeOffset(), FinishDateTimeOffset = zonedDateTimeFinish.ToDateTimeOffset() }; using (ISession session = SessionFactory.OpenSession()) using (ITransaction transaction = session.BeginTransaction()) { session.Save(testLocation); session.Save(testEvent); transaction.Commit(); } ZonedDateTime retrievedZonedDateStart; ZonedDateTime retrievedZonedDateFinish; using (ISession session = SessionFactory.OpenSession()) using (ITransaction transaction = session.BeginTransaction()) { var retrievedEvent = session.Get <DateTimeOffsetTestEntity>(testEvent.Id); retrievedZonedDateStart = retrievedEvent.StartDateTimeOffset.ToZonedDateTime(retrievedEvent.EventLocation.LocationDateTimeZone); retrievedZonedDateFinish = retrievedEvent.FinishDateTimeOffset.ToZonedDateTime(retrievedEvent.EventLocation.LocationDateTimeZone); transaction.Commit(); } Assert.That(zonedDateTimeStart, Is.EqualTo(retrievedZonedDateStart)); Assert.That(zonedDateTimeFinish, Is.EqualTo(retrievedZonedDateFinish)); }
private void Can_Use_NodaTime_ZonedDateTime_In_Document(ZonedDateTime zdt) { using (var documentStore = NewDocumentStore()) { using (var session = documentStore.OpenSession()) { session.Store(new Foo { Id = "foos/1", ZonedDateTime = zdt }); session.SaveChanges(); } using (var session = documentStore.OpenSession()) { var foo = session.Load <Foo>("foos/1"); Assert.Equal(zdt, foo.ZonedDateTime); } using (var session = documentStore.OpenSession()) { var command = new GetDocumentsCommand("foos/1", null, false); session.Advanced.RequestExecutor.Execute(command, session.Advanced.Context); var json = (BlittableJsonReaderObject)command.Result.Results[0]; System.Diagnostics.Debug.WriteLine(json.ToString()); var expectedDateTime = zdt.ToDateTimeOffset().ToString("o"); var expectedZone = zdt.Zone.Id; json.TryGetMember("ZonedDateTime", out var obj); var bInterval = obj as BlittableJsonReaderObject; bInterval.TryGet("OffsetDateTime", out string value1); bInterval.TryGet("Zone", out string value2); Assert.Equal(expectedDateTime, value1); Assert.Equal(expectedZone, value2); } } }
private static void ParseEventTimestamps(string bodyString, string timezone, ref Event evt) { var tz = DateTimeZoneProviders.Tzdb.GetZoneOrNull(timezone); if (tz == null) { throw new InvalidTimeZoneException(); } var results = DateTimeRecognizer.RecognizeDateTime(bodyString, Culture.English); if (results.Count > 0 && results.Any(r => r.TypeName.StartsWith("datetimeV2"))) { var first = results .Where(r => r.Resolution != null) .SkipWhile(r => { var v = (IList <Dictionary <string, string> >)r.Resolution["values"]; var returnValue = v.Any(x => { try { return(x["value"] == "not resolved"); } catch (KeyNotFoundException) { return(false); } }); return(returnValue); }) .FirstOrDefault(); if (first == null) { throw new EventParseException(); } var resolutionValues = (IList <Dictionary <string, string> >)first.Resolution["values"]; var subType = first.TypeName.Split('.').Last(); if (subType == "date") { string timex = resolutionValues.Select(v => v["timex"]).FirstOrDefault(); string value = resolutionValues.Select(v => v["value"]).FirstOrDefault(); if (timex.StartsWith("XXXX-")) { value = value.Substring(4); value = string.Format("{0}{1}", DateTime.Now.Year, value); } LocalDateTime startDateTime = _dateOnlyPattern.Parse(value).Value; ZonedDateTime zonedStartDateTime = tz.AtLeniently(startDateTime); if (IsFuture(zonedStartDateTime.ToDateTimeOffset())) { evt.StartTimestamp = zonedStartDateTime.ToDateTimeOffset(); evt.EndTimestamp = zonedStartDateTime.ToDateTimeOffset().AddHours(1); } else { throw new DateTimeInPastException(); } } else if (subType.Contains("date") && !subType.Contains("range")) { string timex = resolutionValues.Select(v => v["timex"]).FirstOrDefault(); string value = resolutionValues.Select(v => v["value"]).FirstOrDefault(); if (timex.StartsWith("XXXX-")) { value = value.Substring(4); value = string.Format("{0}{1}", DateTime.Now.Year, value); } LocalDateTime startDateTime = _dateTimePattern.Parse(value).Value; ZonedDateTime zonedStartDateTime = tz.AtLeniently(startDateTime); if (IsFuture(zonedStartDateTime.ToDateTimeOffset())) { evt.StartTimestamp = zonedStartDateTime.ToDateTimeOffset(); evt.EndTimestamp = zonedStartDateTime.ToDateTimeOffset().AddHours(1); } else { throw new DateTimeInPastException(); } } else if (subType.Contains("date") && subType.Contains("range")) { string timex = resolutionValues.First()["timex"].TrimStart('(').TrimEnd(')'); string[] timexSplit = timex.Split(','); string fromString = resolutionValues.First()["start"]; string toString = resolutionValues.First()["end"]; if (timexSplit[0].StartsWith("XXXX-")) { fromString = fromString.Substring(4); fromString = string.Format("{0}{1}", DateTime.Now.Year, fromString); } Console.WriteLine(timexSplit.Length); if (timexSplit.Length > 1 && timexSplit[1].StartsWith("XXXX-")) { toString = toString.Substring(4); toString = string.Format("{0}{1}", DateTime.Now.Year, toString); } LocalDateTime from, to; if (fromString.Length == 10) { from = _dateOnlyPattern.Parse(fromString).Value; } else { from = _dateTimePattern.Parse(fromString).Value; } if (toString.Length == 10) { to = _dateOnlyPattern.Parse(toString).Value; } else { to = _dateTimePattern.Parse(toString).Value; } ZonedDateTime zonedFrom = tz.AtLeniently(from); ZonedDateTime zonedTo = tz.AtLeniently(to); if (IsFuture(zonedFrom.ToDateTimeOffset()) && IsFuture(zonedTo.ToDateTimeOffset())) { evt.StartTimestamp = zonedFrom.ToDateTimeOffset(); evt.EndTimestamp = zonedTo.ToDateTimeOffset(); if (IsEventEndBeforeStart(evt)) { throw new EventEndBeforeStartException(); } } else { throw new DateTimeInPastException(); } } else if (subType.Contains("time") && !subType.Contains("range")) { var clock = SystemClock.Instance; LocalDate today = clock.InZone(tz).GetCurrentDate(); string timeString = resolutionValues.Select(v => v["value"]).FirstOrDefault(); string dateTimeString = string.Format("{0} {1}", today.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), timeString); LocalDateTime startDateTime = _dateTimePattern.Parse(dateTimeString).Value; ZonedDateTime zonedStartDateTime = tz.AtLeniently(startDateTime); if (IsFuture(zonedStartDateTime.ToDateTimeOffset())) { evt.StartTimestamp = zonedStartDateTime.ToDateTimeOffset(); evt.EndTimestamp = zonedStartDateTime.ToDateTimeOffset().AddHours(1); } else { throw new DateTimeInPastException(); } } else if (subType.Contains("time") && subType.Contains("range")) { var clock = SystemClock.Instance; LocalDate today = clock.InZone(tz).GetCurrentDate(); string fromString = resolutionValues.First()["start"]; string toString = resolutionValues.First()["end"]; string fromDateTimeString = string.Format("{0} {1}", today.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), fromString); string toDateTimeString = string.Format("{0} {1}", today.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), toString); LocalDateTime startDateTime = _dateTimePattern.Parse(fromDateTimeString).Value; ZonedDateTime zonedStartDateTime = tz.AtLeniently(startDateTime); LocalDateTime endDateTime = _dateTimePattern.Parse(toDateTimeString).Value; ZonedDateTime zonedEndDateTime = tz.AtLeniently(endDateTime); if (IsFuture(zonedStartDateTime.ToDateTimeOffset()) && IsFuture(zonedEndDateTime.ToDateTimeOffset())) { evt.StartTimestamp = zonedStartDateTime.ToDateTimeOffset(); evt.EndTimestamp = zonedEndDateTime.ToDateTimeOffset(); if (IsEventEndBeforeStart(evt)) { throw new EventEndBeforeStartException(); } } else { throw new DateTimeInPastException(); } } else { throw new EventParseException(); } evt.Name = bodyString.RemoveCaseInsensitive(first.Text); } else { throw new EventParseException(); } }
protected override DateTimeOffset GetProperty1Value(ZonedDateTime value) => value.ToDateTimeOffset();
public static string GetFriendlyZonedDateTimeString(this ZonedDateTime zonedDateTime) { return(zonedDateTime.ToDateTimeOffset().ToString("f")); }
public static DateTimeOffset NowInCentralEuropeanTime() { var zonedDateTime = new ZonedDateTime(SystemClock.Instance.GetCurrentInstant(), DateTimeZoneProviders.Tzdb["Europe/Paris"]); return(zonedDateTime.ToDateTimeOffset()); }
private DateTime ConvertZonedDateTime(ZonedDateTime zonedDateTime) { return(zonedDateTime.ToDateTimeOffset().DateTime); }