private void Can_Use_NodaTime_ZonedDateTime_In_Dynamic_Index(ZonedDateTime zdt) { using (var documentStore = NewDocumentStore()) { documentStore.ConfigureForNodaTime(); using (var session = documentStore.OpenSession()) { session.Store(new Foo { Id = "foos/1", ZonedDateTime = zdt }); session.Store(new Foo { Id = "foos/2", ZonedDateTime = zdt - Duration.FromMinutes(1) }); session.Store(new Foo { Id = "foos/3", ZonedDateTime = zdt - Duration.FromMinutes(2) }); session.SaveChanges(); } WaitForUserToContinueTheTest(documentStore); using (var session = documentStore.OpenSession()) { // .ToInstant() is required for dynamic query. See comments in the static index for an alternative. var q1 = session.Query <Foo>().Customize(x => x.WaitForNonStaleResults()) .Where(x => x.ZonedDateTime.ToInstant() == zdt.ToInstant()); Debug.WriteLine(q1); var results1 = q1.ToList(); WaitForUserToContinueTheTest(documentStore); Assert.Equal(1, results1.Count); var q2 = session.Query <Foo>().Customize(x => x.WaitForNonStaleResults()) .Where(x => x.ZonedDateTime.ToInstant() < zdt.ToInstant()) .OrderBy(x => x.ZonedDateTime.ToInstant()); var results2 = q2.ToList(); Assert.Equal(2, results2.Count); Assert.True(results2[0].ZonedDateTime < results2[1].ZonedDateTime); var q3 = session.Query <Foo>().Customize(x => x.WaitForNonStaleResults()) .Where(x => x.ZonedDateTime.ToInstant() <= zdt.ToInstant()) .OrderBy(x => x.ZonedDateTime.ToInstant()); var results3 = q3.ToList(); Assert.Equal(3, results3.Count); Assert.True(results3[0].ZonedDateTime < results3[1].ZonedDateTime); Assert.True(results3[1].ZonedDateTime < results3[2].ZonedDateTime); } } }
/// <summary> /// Get a random date between start and end. /// </summary> public ZonedDateTime Between(ZonedDateTime start, ZonedDateTime end) { //TODO: check for mis matched zones? var min = Instant.Min(start.ToInstant(), end.ToInstant()); var max = Instant.Max(start.ToInstant(), end.ToInstant()); var total = max - min; var partTicks = Random.Double() * total.TotalTicks; var part = Duration.FromTicks(partTicks); return(new(min + part, start.Zone)); }
public TimeInterval(ZonedDateTime point, TimePeriod period) { Ensure.Comparable.Is(point.ToInstant(), TimeInterval.StartOfInterval(point, period).ToInstant(), nameof(point)); _period = period; _start = point; }
private int DateToPixels(long originSeconds, ZonedDateTime dt) { var seconds = dt.ToInstant().ToUnixTimeSeconds(); var px = (seconds - originSeconds) / zoomFormats.SecondsPerPixel; return(Convert.ToInt32(px)); }
// From http://stackoverflow.com/questions/15211052/what-is-the-system-timezoneinfo-isdaylightsavingtime-equivalent-in-nodatime // Thanks to Matt Johnson public static bool IsDaylightSavingsTime(ZonedDateTime zonedDateTime) { Instant instant = zonedDateTime.ToInstant(); ZoneInterval zoneInterval = zonedDateTime.Zone.GetZoneInterval(instant); return(zoneInterval.Savings != Offset.Zero); }
public void Can_Query_By_Equals_ZonedDateTime_Stored_As_DateTimeOffset() { var timeZone = DateTimeZoneProviders.Tzdb.GetSystemDefault(); Instant now = TestClock.Now; ZonedDateTime startZonedDateTime = now.InZone(timeZone); ZonedDateTime finishZonedDateTime = startZonedDateTime.Plus(Duration.FromHours(1)); var testEvent = new ZonedDateTimeTestEntity { Description = "Can_Query_By_Equals_ZonedDateTime_Stored_As_DateTimeOffset", StartZonedDateTime = startZonedDateTime, FinishZonedDateTime = finishZonedDateTime }; using (ISession session = SessionFactory.OpenSession()) using (ITransaction transaction = session.BeginTransaction()) { session.Save(testEvent); transaction.Commit(); } var searchTime = new ZonedDateTime(finishZonedDateTime.ToInstant(), finishZonedDateTime.Zone); using (ISession session = SessionFactory.OpenSession()) using (ITransaction transaction = session.BeginTransaction()) { var query = session.Query <ZonedDateTimeTestEntity>().Where(x => x.FinishZonedDateTime == searchTime); var retrievedEvent = query.SingleOrDefault(); transaction.Commit(); Assert.That(testEvent, Is.Not.Null); Assert.That(testEvent, Is.EqualTo(retrievedEvent)); } }
public static IEnumerable <ZonedDateTime> FromDuration(ZonedDateTime start, ZonedDateTime end, Duration duration) { Ensure.Bool.IsTrue(start.ToInstant() < end.ToInstant()); var range = new ZonedDateTimeRange(start, end); return(FromDuration(range, duration)); }
/// <summary> /// Returns the duration to the given next time (UTC). /// </summary> /// <param name="next">The next date time (UTC).</param> /// <param name="now">The current time instant.</param> /// <returns>The duration.</returns> public static Duration GetDurationToNextUtc( ZonedDateTime next, [CanBeDefault] Instant now) { Debug.NotDefault(next, nameof(next)); return(next.ToInstant() - now); }
/// <summary> /// Checks whether two zoned datetimes are roughly the same (i.e. within some number of /// seconds of each other) or greater/smaller. /// </summary> /// <param name="zdt1">First zoned datetime to compare.</param> /// <param name="zdt2">Second zoned datetime to compare.</param> /// <returns>1: zdt1 > zdt2, -1: zdt1 < zdt2, 0: roughly the same</returns> protected int InexactCompareTo(ZonedDateTime zdt1, ZonedDateTime zdt2) { int seconds = 30; // Convert to ticks (10,000 ticks in a millisecond) int ticks = seconds * (int)1e3 * (int)1e4; // Roughly the same if (Math.Abs(zdt1.ToInstant().Ticks - zdt2.ToInstant().Ticks) <= ticks) { return(0); } else { return(zdt1.ToInstant().Ticks > zdt2.ToInstant().Ticks ? 1 : -1); } }
//https://stackoverflow.com/a/58497143 public static bool IsDaylightSavingsTime(this ZonedDateTime timeInZone) { var instant = timeInZone.ToInstant(); var zoneInterval = timeInZone.Zone.GetZoneInterval(instant); return(zoneInterval.Savings != Offset.Zero); }
/// <summary> /// Initializes a new instance of the <see cref="OneOffSchedule" /> class. /// </summary> /// <param name="name">An optional name for the schedule.</param> /// <param name="zonedDateTime">The date and time.</param> /// <param name="options">The options.</param> public OneOffSchedule( [CanBeNull] string name, ZonedDateTime zonedDateTime, ScheduleOptions options = ScheduleOptions.None) { _name = name; Instant = zonedDateTime.ToInstant(); _options = options; }
public static Instant GetMonthEndInstant(this LocalDate forDate, DateTimeZone timeZone) { ZonedDateTime zonedStartDateTime = timeZone.AtStartOfDay(forDate); CalendarSystem calendar = zonedStartDateTime.Calendar; int daysInMonth = calendar.GetDaysInMonth(zonedStartDateTime.Year, zonedStartDateTime.Month); ZonedDateTime zonedEndDateTime = timeZone.AtStartOfDay(new LocalDate(zonedStartDateTime.Year, zonedStartDateTime.Month, daysInMonth)); return(zonedEndDateTime.ToInstant()); }
public static bool ZonedDateTimeConverter(string fieldname, ZonedDateTime value, QueryValueConvertionType type, out string strValue) { var instant = value.ToInstant(); NodaUtil.Instant.Validate(instant); strValue = instant.ToString(NodaUtil.Instant.FullIsoPattern.PatternText, null); return(true); }
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 Construction() { ZonedDateTime dt = Dublin.AtStrictly(new LocalDateTime(2010, 6, 9, 15, 15, 0)); Assert.AreEqual(15, dt.Hour); Assert.AreEqual(2010, dt.Year); Instant instant = Instant.FromUtc(2010, 6, 9, 14, 15, 0); Assert.AreEqual(instant, dt.ToInstant()); }
void INpgsqlSimpleTypeHandler <ZonedDateTime> .Write(ZonedDateTime value, NpgsqlWriteBuffer buf, NpgsqlParameter?parameter) { var instant = value.ToInstant(); if (!DisableDateTimeInfinityConversions && (instant == Instant.MaxValue || instant == Instant.MinValue)) { throw new InvalidCastException("Infinity values not supported for timestamp with time zone"); } _wrappedHandler.Write(instant, buf, parameter); }
/*public static Dictionary<Event.Rule, Instant> GetOccurrences(this Event self, Instant from, Instant to) * { * Dictionary<Instant, Event.Rule> results = new Dictionary<Instant, Event.Rule>(); * foreach (Event.Rule rule in self.Rules) * { * List<Instant> occurrences = rule.GetOccurrences(self, from, to); * results.Add(rule, occurrences); * } * * return results; * }*/ public static Instant GetInstant(this Event self, LocalTime time) { if (self.BaseTimeZone == null) { throw new Exception("Non repeating event missing base time zone"); } LocalDateTime ldt = (LocalDate)self.BeginDate + time; ZonedDateTime zdt = ldt.InZoneLeniently(self.BaseTimeZone); return(zdt.ToInstant()); }
/// <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 static int GetDaysTill(Instant instant, DateTimeZone zone) { ZonedDateTime zdt = TimeUtils.Now.InZone(zone); LocalDateTime ldt = zdt.LocalDateTime; ldt = ldt.Date.AtMidnight(); zdt = ldt.InZoneLeniently(zone); Duration duration = instant - zdt.ToInstant(); return((int)Math.Floor(duration.TotalDays)); }
public void Construction() { DateTimeZone dublin = DateTimeZoneProviders.Tzdb["Europe/Dublin"]; ZonedDateTime dt = Snippet.For(dublin.AtStrictly(new LocalDateTime(2010, 6, 9, 15, 15, 0))); Assert.AreEqual(15, dt.Hour); Assert.AreEqual(2010, dt.Year); Instant instant = Instant.FromUtc(2010, 6, 9, 14, 15, 0); Assert.AreEqual(instant, dt.ToInstant()); }
/// <summary> /// Returns the offset milliseconds of the given time floored from the given duration. /// </summary> /// <param name="time">The time.</param> /// <param name="duration">The duration.</param> /// <returns>The milliseconds offset.</returns> public static int FloorOffsetMilliseconds(this ZonedDateTime time, Duration duration) { Debug.NotDefault(time, nameof(time)); Debug.NotDefault(duration, nameof(duration)); var durationMs = duration.TotalMilliseconds; var unixMs = time.ToInstant().ToUnixTimeMilliseconds(); var floored = Math.Floor(unixMs / durationMs) * durationMs; return((int)(unixMs - floored)); }
/// <summary> /// Returns the offset milliseconds of the given time ceiling from the given duration. /// </summary> /// <param name="time">The time.</param> /// <param name="duration">The duration.</param> /// <returns>The milliseconds offset.</returns> public static int CeilingOffsetMilliseconds(this ZonedDateTime time, Duration duration) { Debug.NotDefault(time, nameof(time)); Debug.NotDefault(duration, nameof(duration)); var durationMs = duration.TotalMilliseconds; var unixMs = time.ToInstant().ToUnixTimeMilliseconds(); var ceiling = Math.Ceiling(unixMs / durationMs) * durationMs; return((int)(ceiling - unixMs)); }
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 void Construction() { ZonedDateTime dt = Dublin.AtStrictly(new LocalDateTime(2010, 6, 9, 15, 15, 0)); Assert.AreEqual(15, dt.Hour); Assert.AreEqual(2010, dt.Year); // Not 21... we're not in the Gregorian calendar! Assert.AreEqual(20, dt.CenturyOfEra); Instant instant = Instant.FromUtc(2010, 6, 9, 14, 15, 0); Assert.AreEqual(instant, dt.ToInstant()); }
public void WithZone() { Instant instant = Instant.FromUtc(2012, 2, 4, 12, 35); ZonedDateTime zoned = new ZonedDateTime(instant, SampleZone); Assert.AreEqual(new LocalDateTime(2012, 2, 4, 16, 35, 0), zoned.LocalDateTime); // Will be UTC-8 for our instant. DateTimeZone newZone = new SingleTransitionDateTimeZone(Instant.FromUtc(2000, 1, 1, 0, 0), -7, -8); ZonedDateTime converted = zoned.WithZone(newZone); Assert.AreEqual(new LocalDateTime(2012, 2, 4, 4, 35, 0), converted.LocalDateTime); Assert.AreEqual(converted.ToInstant(), instant); }
public void Update(Size availableSize, Instant firstVisibleDay) { ColumnWidth = LayoutHelper.RoundLayoutValue(availableSize.Width / ColumnsCount); if (DoubleUtil.GreaterThanOrClose(ColumnWidth * ColumnsCount, availableSize.Width) == true) { ColumnWidth = LayoutHelper.FloorLayoutValue(availableSize.Width / ColumnsCount); } RowsHeight = LayoutHelper.RoundLayoutValue(availableSize.Height / RowsCount); if (DoubleUtil.GreaterThanOrClose(RowsHeight * RowsCount, availableSize.Height) == true) { RowsHeight = LayoutHelper.FloorLayoutValue(availableSize.Height / RowsCount); } GridCellSize = new Size(ColumnWidth, RowsHeight); Bounds = LayoutHelper.RoundLayoutRect3(new Rect(0, 0, ColumnWidth * ColumnsCount, RowsHeight * RowsCount)); double columnOffset = 0; Grid = new MonthViewDay[RowsCount][]; IClock systemClock = SystemClock.Instance; Instant now = systemClock.GetCurrentInstant(); DateTimeZone tz = DateTimeZoneProviders.Tzdb.GetSystemDefault(); LocalDate today = now.InZone(tz).Date; ZonedDateTime currentDay = tz.AtStartOfDay(today); for (int rowIndex = 0; rowIndex < RowsCount; rowIndex++) { columnOffset = 0; Grid[rowIndex] = new MonthViewDay[ColumnsCount]; for (int columnIndex = 0; columnIndex < ColumnsCount; columnIndex++) { // ColumnWidth and RowHeight should be already layout rounded - so no need to round the rect bounds var day = new MonthViewDay(); day.GridCell = new Rect(columnIndex * ColumnWidth, rowIndex * RowsHeight, ColumnWidth, RowsHeight); var nextDay = currentDay.Plus(NodaTime.Duration.FromDays(1)); day.Day = new Interval(currentDay.ToInstant(), nextDay.ToInstant()); // may be we should use 23:59:99999 as end interval????? currentDay = nextDay; Grid[rowIndex][columnIndex] = day; } columnOffset += ColumnWidth; } }
/// <summary> /// Converts a local-time DateTime to UTC DateTime based on the specified /// timezone. The returned object will be of UTC DateTimeKind. To be used /// when we want to know what's the UTC representation of the time somewhere /// in the world. /// </summary> /// <param name="dateTime">Local DateTime as UTC or Unspecified DateTimeKind.</param> /// <returns>UTC DateTime as UTC DateTimeKind.</returns> internal static DateTime ToUTC(this DateTime localDateTime) { if (localDateTime.Kind == DateTimeKind.Local) { return(localDateTime.ToUniversalTime()); } DateTimeZone zone = CultureHelper.GetDateTimeZone(); LocalDateTime asLocal = localDateTime.ToLocalDateTime(); ZonedDateTime asZoned = asLocal.InZoneLeniently(zone); Instant instant = asZoned.ToInstant(); ZonedDateTime asZonedInUtc = instant.InUtc(); return(asZonedInUtc.ToDateTimeUtc()); }
/// <summary> /// Converts a local-time DateTime to UTC DateTime based on the specified /// timezone. The returned object will be of UTC DateTimeKind. To be used /// when we want to know what's the UTC representation of the time somewhere /// in the world. /// </summary> /// <param name="dateTime">Local DateTime as UTC or Unspecified DateTimeKind.</param> /// <param name="timezone">Timezone name (in TZDB format).</param> /// <returns>UTC DateTime as UTC DateTimeKind.</returns> public static DateTime InZone(this DateTime dateTime, string timezone) { if (dateTime.Kind == DateTimeKind.Local) { throw new ArgumentException("Expected non-local kind of DateTime"); } var zone = DateTimeZoneProviders.Tzdb[timezone]; LocalDateTime asLocal = dateTime.ToLocalDateTime(); ZonedDateTime asZoned = asLocal.InZoneLeniently(zone); Instant instant = asZoned.ToInstant(); ZonedDateTime asZonedInUtc = instant.InUtc(); DateTime utc = asZonedInUtc.ToDateTimeUtc(); return(utc); }
/// <summary> /// Converts the given object to the type of this converter, 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">The <see cref="T:System.Globalization.CultureInfo"/> to use as the current culture. </param> /// <param name="value">The <see cref="T:System.Object"/> to convert. </param> /// <exception cref="T:System.NotSupportedException">The conversion cannot be performed. </exception> public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { string @string = value as string; if (@string != null) { Instant instant; if (TimeHelpers.GetInstantPatterns(culture).TryParseAny(@string.Trim(), out instant)) { return(instant); } DateTimeOffset dateTimeOffset; if (DateTimeOffset.TryParse(@string, out dateTimeOffset)) { return(Instant.FromDateTimeOffset(dateTimeOffset)); } throw new NotSupportedException( // ReSharper disable once AssignNullToNotNullAttribute string.Format(Resources.InstantConverter_ConvertFrom_CannotParse, @string)); } if (value is DateTime) { DateTime dateTime = (DateTime)value; return(Instant.FromDateTimeUtc(dateTime.ToUniversalTime())); } if (value is DateTimeOffset) { DateTimeOffset dateTimeOffset = (DateTimeOffset)value; return(Instant.FromDateTimeOffset(dateTimeOffset)); } if (value is OffsetDateTime) { OffsetDateTime offsetDateTime = (OffsetDateTime)value; return(offsetDateTime.ToInstant()); } if (value is ZonedDateTime) { ZonedDateTime zonedDateTime = (ZonedDateTime)value; return(zonedDateTime.ToInstant()); } return(base.ConvertFrom(context, culture, value)); }
private Instant ToInstantFromLocal(DateTime dt, DateTimeZone timeZone, bool assert = false) { LocalDateTime localDateTime = new LocalDateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, dt.Millisecond); ZonedDateTime dateTimeZoned = localDateTime.InZoneLeniently(timeZone); Instant instant = dateTimeZoned.ToInstant(); if (assert) { var dateTimeZoned_ = instant.InZone(timeZone); LocalDateTime localDateTime_ = dateTimeZoned_.LocalDateTime; if (!LocalDateTimeEquals(dt, localDateTime_)) { throw new ArgumentException($"{nameof(ToInstantFromLocal)}: Reverse datetime-conversion test failed."); } } return(instant); }
/// <summary> /// Choose a random date and time within a given range. /// </summary> /// <param name="minimum">The minimum date possible.</param> /// <param name="maximum">The maximum date possible.</param> /// <returns> /// A <see cref="T:System.ZonedDateTime"/> between <paramref name="minimum"/> and <paramref name="maximum"/>. /// </returns> private static ZonedDateTime RandomZonedDateTime(ZonedDateTime minimum, ZonedDateTime maximum) { return minimum + Duration.FromTicks((long)((maximum.ToInstant() - minimum.ToInstant()).Ticks * Random.NextDouble())); }