private void ValidateZoneEquality(Instant instant, DateTimeZone nodaZone, TimeZoneInfo windowsZone)
        {
            // The BCL is basically broken (up to and including .NET 4.5.1 at least) around its interpretation
            // of its own data around the new year. See http://codeblog.jonskeet.uk/2014/09/30/the-mysteries-of-bcl-time-zone-data/
            // for details. We're not trying to emulate this behaviour.
            // It's a lot *better* for .NET 4.6,
            var utc = instant.InUtc();

            if ((utc.Month == 12 && utc.Day == 31) || (utc.Month == 1 && utc.Day == 1))
            {
                return;
            }

            var interval = nodaZone.GetZoneInterval(instant);

            // Check that the zone interval really represents a transition. It could be a change in
            // wall offset, name, or the split between standard time and daylight savings for the interval.
            if (interval.RawStart != Instant.BeforeMinValue)
            {
                var previousInterval = nodaZone.GetZoneInterval(interval.Start - Duration.Epsilon);
                Assert.AreNotEqual(new { interval.WallOffset, interval.Name, interval.StandardOffset },
                                   new { previousInterval.WallOffset, previousInterval.Name, previousInterval.StandardOffset },
                                   "Non-transition from {0} to {1}", previousInterval, interval);
            }
            var nodaOffset    = interval.WallOffset;
            var windowsOffset = windowsZone.GetUtcOffset(instant.ToDateTimeUtc());

            Assert.AreEqual(windowsOffset, nodaOffset.ToTimeSpan(), $"Incorrect offset at {instant} in interval {interval}");
            var bclDaylight = windowsZone.IsDaylightSavingTime(instant.ToDateTimeUtc());

            Assert.AreEqual(bclDaylight, interval.Savings != Offset.Zero,
                            $"At {instant}, BCL IsDaylightSavingTime={bclDaylight}; Noda savings={interval.Savings}");
        }
Example #2
0
        static void Main(string[] args)
        {
            // Instant represents time from epoch
            Instant now = SystemClock.Instance.GetCurrentInstant();

            // Convert an instant to a ZonedDateTime
            ZonedDateTime nowInIsoUtc = now.InUtc();

            // Create a duration
            Duration duration = Duration.FromMinutes(3);

            // Add it to our ZonedDateTime
            ZonedDateTime thenInIsoUtc = nowInIsoUtc + duration;

            // Time zone support (multiple providers)
            var london = DateTimeZoneProviders.Tzdb["Asia/Bangkok"];

            // Time zone conversions
            var localDate = new LocalDateTime();
            var before    = london.AtStrictly(localDate);

            Console.WriteLine(localDate);
            Console.WriteLine(before);
            Console.ReadKey();
        }
        public void DepositCheque(Guid chequeId, double amount, IClock clock, CorrelatedMessage source)
        {
            if (amount <= 0)
            {
                throw new InvalidOperationException("Cheque's amount must be strictly positive");
            }

            var depositTime = clock.GetCurrentInstant();

            Instant clearanceTime = depositTime;

            switch (clearanceTime.InUtc().DayOfWeek)
            {
            case IsoDayOfWeek.Saturday:
                clearanceTime.Plus(Duration.FromDays(2));
                break;

            case IsoDayOfWeek.Sunday:
                clearanceTime.Plus(Duration.FromDays(1));
                break;
            }

            Raise(new ChequeDeposited(source)
            {
                AccountId     = Id,
                ChequeId      = chequeId,
                Amount        = amount,
                DepositTime   = depositTime,
                ClearanceTime = clearanceTime
            });
        }
Example #4
0
        private void ValidateZoneEquality(Instant instant, DateTimeZone nodaZone, TimeZoneInfo windowsZone)
        {
            // The BCL is basically broken (up to and including .NET 4.5.1 at least) around its interpretation
            // of its own data around the new year. See http://codeblog.jonskeet.uk/2014/09/30/the-mysteries-of-bcl-time-zone-data/
            // for details. We're not trying to emulate this behaviour.
            // It's a lot *better* for .NET 4.6,
            // FIXME: Finish this comment, try again. (We don't test against .NET 4.5 any more...)
            var utc = instant.InUtc();

            if ((utc.Month == 12 && utc.Day == 31) || (utc.Month == 1 && utc.Day == 1))
            {
                return;
            }

            var interval = nodaZone.GetZoneInterval(instant);

            // Check that the zone interval really represents a transition. It could be a change in
            // wall offset, name, or the split between standard time and daylight savings for the interval.
            if (interval.RawStart != Instant.BeforeMinValue)
            {
                var previousInterval = nodaZone.GetZoneInterval(interval.Start - Duration.Epsilon);
                Assert.AreNotEqual(new { interval.WallOffset, interval.Name, interval.StandardOffset },
                                   new { previousInterval.WallOffset, previousInterval.Name, previousInterval.StandardOffset },
                                   "Non-transition from {0} to {1}", previousInterval, interval);
            }
            var nodaOffset = interval.WallOffset;

            // Some midnight transitions in the Noda Time representation are actually corrections for the
            // BCL data indicating 23:59:59.999 on the previous day. If we're testing around midnight,
            // allow the Windows data to be correct for either of those instants.
            var acceptableInstants = new List <Instant> {
                instant
            };
            var localTimeOfDay = instant.InZone(nodaZone).TimeOfDay;

            if ((localTimeOfDay == LocalTime.Midnight || localTimeOfDay == LocalTime.MaxValue) && instant > NodaConstants.BclEpoch)
            {
                acceptableInstants.Add(instant - Duration.FromMilliseconds(1));
            }

            var expectedOffsetAsTimeSpan = nodaOffset.ToTimeSpan();

            // Find an instant that at least has the right offset (so will pass the first assertion).
            var instantToTest = acceptableInstants.FirstOrDefault(candidate => windowsZone.GetUtcOffset(candidate.ToDateTimeUtc()) == expectedOffsetAsTimeSpan);

            // If the test is definitely going to fail, just use the original instant that was passed in.
            if (instantToTest == default)
            {
                instantToTest = instant;
            }

            var windowsOffset = windowsZone.GetUtcOffset(instantToTest.ToDateTimeUtc());

            Assert.AreEqual(windowsOffset, expectedOffsetAsTimeSpan, "Incorrect offset at {0} in interval {1}", instantToTest, interval);
            var bclDaylight = windowsZone.IsDaylightSavingTime(instantToTest.ToDateTimeUtc());

            Assert.AreEqual(bclDaylight, interval.Savings != Offset.Zero,
                            "At {0}, BCL IsDaylightSavingTime={1}; Noda savings={2}",
                            instant, bclDaylight, interval.Savings);
        }
        private void TimeToJSON()
        {
            Instant        now          = SystemClock.Instance.Now;
            String         timeZone     = TimeZoneInfo.Local.DisplayName;
            long           ticks        = now.Ticks;
            String         timeZoneStan = TimeZoneInfo.Local.StandardName;
            String         timeZoneId   = TimeZoneInfo.Local.Id;
            var            nowUtc       = now.InUtc();
            DateTimeOffset odt          = DateTimeOffset.Now;
            DateTime       dt           = odt.DateTime;

            DateTimeZoneProviders.Serialization = DateTimeZoneProviders.Bcl;
            //var curZone = DateTimeZoneProviders.Tzdb["Canada/Eastern"];
            var    curZone     = DateTimeZoneProviders.Bcl[timeZoneId];
            var    nowZone     = now.InZone(curZone);
            var    offset      = nowZone.ToOffsetDateTime();
            var    duration    = NodaTime.Duration.FromMinutes(3);
            var    local       = new LocalDateTime(nowZone.Year, nowZone.Month, nowZone.Day, nowZone.Hour, nowZone.Minute, nowZone.Second, nowZone.Millisecond);
            var    localInUtc  = local.InUtc();
            var    inst        = localInUtc.ToInstant();
            var    odtToStr    = odt.ToString("yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture);
            var    offsetToStr = offset.ToString("yyyy-MM-ddTHH:mm:ss.ffffffo<m>", CultureInfo.InvariantCulture);
            String nowStr      = JsonConvert.SerializeObject(now, Formatting.None, settings);
            String offSet      = JsonConvert.SerializeObject(offset, Formatting.Indented, settings);
            String utc         = JsonConvert.SerializeObject(nowUtc, Formatting.None, settings);
            String dur         = JsonConvert.SerializeObject(duration, Formatting.None, settings);
            String loc         = JsonConvert.SerializeObject(local, Formatting.None, settings);
            String loc2Str     = local.ToString();

            //JSONText = String.Format("Time: {0}\nOffset: {1}\nUtc time: {2}\nZoned time: {3}\nTime zone name: {4}\nTime zone name standard: {5}\nLocal time: {6}\nTostr local: {7}\nTicks: {8}",
            //                            nowStr, offSet, utc, nowZone, timeZone, timeZoneStan, loc, loc2Str, ticks);
            JSONText = String.Format("Time: {0}\nOffset: {1}\nZoned time: {2}\nOffset To String: {3}",
                                     nowStr, offSet, nowZone, offset.ToString());
        }
Example #6
0
        /// <summary>
        /// BidAsk AddData
        /// </summary>
        /// <remarks>
        /// Add Data on to the curve with Instant
        /// </remarks>
        /// <returns>AddBidAskOperationResult</returns>
        public AddBidAskOperationResult AddData(Instant time, string product, BidAskValue value)
        {
            if (!_entity.OriginalGranularity.IsTimeGranularity())
            {
                throw new BidAskException("This MarketData has Date granularity. Use AddData(LocalDate date...)");
            }

            return(_addBidAsk(time.InUtc().LocalDateTime, product, value));
        }
Example #7
0
        private Period GetPeriodFromNow(Instant pastInstant)
        {
            var now      = _clock.GetCurrentInstant();
            var today    = now.InUtc().Date;
            var pastDate = pastInstant.InUtc().Date;
            var period   = Period.Between(pastDate, today);

            return(period);
        }
Example #8
0
        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());
        }
Example #9
0
        /// <summary>
        /// If given <see cref="Instant"/> value of parameter <paramref name="calculatedTime"/> has second component larger than zero, the second component is resetted to zero and minute component is added with one.
        /// </summary>
        private static Instant RoundPrayerTime(Instant calculatedTime)
        {
            var utc = calculatedTime.InUtc();

            if (utc.Second > 0)
            {
                calculatedTime = calculatedTime + Duration.FromSeconds(60 - utc.Second);
            }

            return(calculatedTime);
        }
        private Season ResolveSeason(Instant releaseDate)
        {
            var    year  = releaseDate.InUtc().Year;
            var    month = releaseDate.InUtc().Month;
            string seasonPrefix;

            if (month < 4)
            {
                seasonPrefix = "Winter";
            }
            else if (month < 7)
            {
                seasonPrefix = "Spring";
            }
            else if (month < 10)
            {
                seasonPrefix = "Summer";
            }
            else
            {
                seasonPrefix = "Autumn";
            }
            var season = new Season
            {
                Year = year,
                Name = seasonPrefix + " " + year
            };

            var dbSeason = _dbContext.Seasons.FirstOrDefault(_ => _.Name == season.Name);

            if (dbSeason != null)
            {
                return(dbSeason);
            }

            _dbContext.Add(season);
            _dbContext.SaveChanges();

            return(season);
        }
Example #11
0
        /// <summary>
        /// VersionedTimeSerie AddData
        /// </summary>
        /// <remarks>
        /// Add Data on to the curve with Instant
        /// </remarks>
        /// <returns>AddTimeSerieOperationResult</returns>
        public AddTimeSerieOperationResult AddData(Instant time, double?value)
        {
            Ensure.Any.IsNotNull(_entity);

            if (!_entity.OriginalGranularity.IsTimeGranularity())
            {
                throw new VersionedTimeSerieException("This MarketData has Date granularity. Use AddData(LocalDate date, double? value)");
            }

            var localTime = time.InUtc().LocalDateTime;

            return(_add(localTime, value));
        }
Example #12
0
        /// <summary>
        /// AuctionTimeSerie AddData
        /// </summary>
        /// <remarks>
        /// Add Data on to the curve with Instant
        /// </remarks>
        /// <returns>AddAuctionTimeSerieOperationResult</returns>
        public AddAuctionTimeSerieOperationResult AddData(Instant time, AuctionBidValue[] bid, AuctionBidValue[] offer)
        {
            Ensure.Any.IsNotNull(_entity);

            if (!_entity.OriginalGranularity.IsTimeGranularity())
            {
                throw new AuctionTimeSerieException("This MarketData has Date granularity. Use AddData(LocalDate date, AuctionBidValue[] bid, AuctionBidValue[] offer)");
            }

            var localTime = time.InUtc().LocalDateTime;

            return(_add(localTime, bid, offer));
        }
        /// <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)
            {
                LocalDateTime localDateTime;
                if (TimeHelpers.GetLocalDateTimePatterns(culture).TryParseAny(@string.Trim(), out localDateTime))
                {
                    return(localDateTime);
                }

                DateTime dateTime;
                if (DateTime.TryParse(@string, out dateTime))
                {
                    return(LocalDateTime.FromDateTime(dateTime));
                }

                throw new NotSupportedException(
                          // ReSharper disable once AssignNullToNotNullAttribute
                          string.Format(Resources.LocalDateTimeConverter_ConvertFrom_CannotParse, @string));
            }
            if (value is DateTime)
            {
                DateTime dateTime = (DateTime)value;
                return(LocalDateTime.FromDateTime(dateTime));
            }
            if (value is DateTimeOffset)
            {
                DateTimeOffset dateTimeOffset = (DateTimeOffset)value;
                return(LocalDateTime.FromDateTime(dateTimeOffset.LocalDateTime));
            }
            if (value is OffsetDateTime)
            {
                OffsetDateTime offsetDateTime = (OffsetDateTime)value;
                return(offsetDateTime.LocalDateTime);
            }
            if (value is Instant)
            {
                Instant instant = (Instant)value;
                return(instant.InUtc().LocalDateTime);
            }
            if (value is ZonedDateTime)
            {
                ZonedDateTime zonedDateTime = (ZonedDateTime)value;
                return(zonedDateTime.LocalDateTime);
            }

            return(base.ConvertFrom(context, culture, value));
        }
Example #14
0
        static void Main()
        {
            Instant now = SystemClock.Instance.Now;

            Console.WriteLine("now       : {0}", now);
            ZonedDateTime utcNow = now.InUtc();

            Console.WriteLine("utcNow    : {0}", utcNow);
            var poland = DateTimeZoneProviders.Tzdb["Europe/Warsaw"];

            var polandTime = now.InZone(poland);

            Console.WriteLine("in poland : {0}", polandTime);
        }
Example #15
0
        /// <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());
        }
Example #16
0
    /// <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);
    }
Example #17
0
        static void Main(string[] args)
        {
            Instant       now         = SystemClock.Instance.Now;
            ZonedDateTime currentDate = now.InUtc();

            CalculateKosmorDate(currentDate);

            WebClient client = new WebClient();

            string result = client.DownloadString("http://www.kosmor.de/forum/viewforum.php?f=-8");
            string id     = FindCurrentId(result);

            GetNewsPost(id);

            Console.ReadKey();
        }
Example #18
0
        /// <summary>
        /// Convert Instant to ISO 8601 long with millisecond precision
        /// using yyyymmddhhmmssfff format in UTC.
        ///
        /// Error message if equal to the default constructed value.
        /// </summary>
        public static long ToIsoLong(this Instant value)
        {
            // If default constructed datetime is passed, error message
            if (value == InstantUtil.Empty)
            {
                throw new Exception(
                          $"Default constructed (empty) Instant {value} has been passed to ToIsoLong() method.");
            }

            // Convert to zoned date time in UTC timezone, then take LocalDateTime component of the result
            var dateTimeInUtc = value.InUtc().LocalDateTime;

            // Convert the result to long
            long result = dateTimeInUtc.ToIsoLong();

            return(result);
        }
Example #19
0
        /// <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));
            }

            Instant instant = (Instant)value;

            if (destinationType == typeof(string))
            {
                // ReSharper disable once PossibleNullReferenceException
                return(InstantPattern.ExtendedIsoPattern.Format(instant));
            }

            if (destinationType == typeof(DateTime))
            {
                return(instant.ToDateTimeUtc());
            }

            if (destinationType == typeof(DateTimeOffset))
            {
                return(instant.ToDateTimeOffset());
            }

            if (destinationType == typeof(ZonedDateTime))
            {
                return(instant.InUtc());
            }

            if (destinationType == typeof(OffsetDateTime))
            {
                return(OffsetDateTime.FromDateTimeOffset(instant.ToDateTimeOffset()));
            }

            return(base.ConvertTo(context, culture, value, destinationType));
        }
Example #20
0
        /// <summary>
        ///     Generate prayer times for one day at given date.
        /// </summary>
        /// <param name="when">
        ///     <see cref="Instant" /> value which represents the date.
        /// </param>
        /// <param name="settings">
        ///     Settings containing parameters for calculating prayer times.
        /// </param>
        /// <param name="coordinate">
        ///     Location's coordinate.
        /// </param>
        /// <param name="timeZone">
        ///     Location's time zone.
        /// </param>
        /// <returns>
        ///     <see cref="Prayers" /> object containing prayer times for one day at given date.
        /// </returns>
        internal static Prayers GetPrayerTimesForOneDay(Instant when, [NotNull] PrayerCalculationSettings settings, Geocoordinate coordinate, double timeZone)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }

            var utc    = when.InUtc();
            var year   = utc.Year;
            var month  = utc.Month;
            var day    = utc.Day;
            var local  = new LocalDate(year, month, day);
            var newUtc = new ZonedDateTime(local.AtMidnight(), DateTimeZone.Utc, Offset.Zero);

            var jd              = newUtc.ToInstant().ToJulianDate() - (coordinate.Longitude / 360.0);
            var raw             = ComputeRaw(jd, settings, coordinate.Latitude, coordinate.Altitude);
            var afterAdjustment = AdjustTime(raw, settings, coordinate.Longitude, timeZone);

            // Calculate midnight.
            var fajr    = afterAdjustment.Fajr;
            var sunrise = afterAdjustment.Sunrise;
            var sunset  = afterAdjustment.Sunset;

            afterAdjustment.Midnight = ComputeMidnightTime(settings.CalculationMethod.MidnightMethod, fajr, sunrise, sunset);

            // Convert.
            var converted = ConvertFromFloatingPointFormat(afterAdjustment, year, month, day, timeZone);

            // Round.
            var rounded = new Prayers(RoundPrayerTime(converted.Imsak),
                                      RoundPrayerTime(converted.Fajr),
                                      RoundPrayerTime(converted.Sunrise),
                                      RoundPrayerTime(converted.Dhuha),
                                      RoundPrayerTime(converted.Zuhr),
                                      RoundPrayerTime(converted.Asr),
                                      RoundPrayerTime(converted.Sunset),
                                      RoundPrayerTime(converted.Maghrib),
                                      RoundPrayerTime(converted.Isha),
                                      RoundPrayerTime(converted.Midnight));

            return(rounded);
        }
        private void ValidateZoneEquality(Instant instant, DateTimeZone nodaZone, TimeZoneInfo windowsZone)
        {
            // Skip just the first transition in Libya. It's broken in Windows.
            // See issue 220 for the background.
            if (windowsZone.Id == "Libya Standard Time" && instant.InUtc().Year == 2011)
            {
                return;
            }

            var interval = nodaZone.GetZoneInterval(instant);

            // Check that the zone interval really represents a transition.
            if (interval.Start != Instant.MinValue)
            {
                Assert.AreNotEqual(interval.WallOffset, nodaZone.GetUtcOffset(interval.Start - Duration.Epsilon));
            }
            var nodaOffset    = interval.WallOffset;
            var windowsOffset = windowsZone.GetUtcOffset(instant.ToDateTimeUtc());

            Assert.AreEqual(windowsOffset, nodaOffset.ToTimeSpan(), "Incorrect offset at " + instant + " in interval " + interval);
        }
Example #22
0
        private async Task <bool> WasLastRunToday()
        {
            today    = SystemClock.Instance.GetCurrentInstant();
            todayUtc = today.InUtc();

            Instant lastRun = Instant.MinValue;

            try
            {
                // ConfigCache updates every 5 minutes (see JobFac.Library.ConstTimeouts)
                // so it will always be up-to-date since ScheduleWriter is invoked on a
                // 15-minute cycle (also defined in ConstTimeouts).
                var lastRunTimestamp = await configCache.GetValue(ConstConfigKeys.ScheduleWriterLastRunDateUtc);

                lastRun = InstantPattern.General.Parse(lastRunTimestamp).GetValueOrThrow();
            }
            catch
            { }

            return(todayUtc.Date == lastRun.InUtc().Date);
        }
Example #23
0
        /// <summary>
        /// Returns the next date time for the given target local time (UTC).
        /// </summary>
        /// <param name="target">The target time of day.</param>
        /// <param name="now">The current time instant.</param>
        /// <returns>The next date time (UTC).</returns>
        public static ZonedDateTime GetNextUtc([CanBeDefault] LocalTime target, [CanBeDefault] Instant now)
        {
            var localNow    = now.InZone(DateTimeZone.Utc).LocalDateTime;
            var localTarget = new LocalDateTime(
                localNow.Year,
                localNow.Month,
                localNow.Day,
                target.Hour,
                target.Minute,
                target.Second,
                target.Millisecond);

            var nextToday = new ZonedDateTime(localTarget, DateTimeZone.Utc, Offset.Zero);

            if (nextToday.IsLessThanOrEqualTo(now.InUtc()))
            {
                localTarget += Period.FromDays(1);
                nextToday    = new ZonedDateTime(localTarget, DateTimeZone.Utc, Offset.Zero);
            }

            return(nextToday);
        }
Example #24
0
        private static void AssertEqualInstant(Instant expected, Instant actual)
        {
            var expectedUtc    = expected.InUtc();
            var expectedYear   = expectedUtc.Year;
            var expectedMonth  = expectedUtc.Month;
            var expectedDay    = expectedUtc.Day;
            var expectedHour   = expectedUtc.Hour;
            var expectedMinute = expectedUtc.Minute;

            var actualUtc    = actual.InUtc();
            var actualYear   = actualUtc.Year;
            var actualMonth  = actualUtc.Month;
            var actualDay    = actualUtc.Day;
            var actualHour   = actualUtc.Hour;
            var actualMinute = actualUtc.Minute;

            Assert.Equal(expectedYear, actualYear);
            Assert.Equal(expectedMonth, actualMonth);
            Assert.Equal(expectedDay, actualDay);
            Assert.Equal(expectedHour, actualHour);
            Assert.Equal(expectedMinute, actualMinute);
        }
Example #25
0
        /// <summary>
        /// Serializes the <see cref="Instant"/> for SQL Server queries.
        /// </summary>
        /// <param name="instant">An instant.</param>
        /// <param name="decimalPlaces">Number of digits after the decimal. Must be between 0 and 7 (both included).</param>
        /// <returns>A SQL formatted string representation of <paramref name="instant"/>.</returns>
        /// <seealso cref="ToQuotedSqlString(Instant)"/>
        public static string ToSqlString(this Instant instant, int decimalPlaces)
        {
            if (decimalPlaces < 0 || 7 < decimalPlaces)
            {
                throw new ArgumentOutOfRangeException(nameof(decimalPlaces), "Value must be between 0 and 7 (both included).");
            }

            if (instant.InUtc().TimeOfDay == LocalTime.Midnight)
            {
                return(PatternWithoutTime.Format(instant));
            }

            if (decimalPlaces == 7)
            {
                return(PatternWithSevenDecimalPlaces.Format(instant));
            }

            if (decimalPlaces == 0)
            {
                return(PatternWithNoDecimalPlaces.Format(instant));
            }

            return(InstantPattern.CreateWithInvariantCulture(@"yyyy'-'MM'-'dd HH':'mm':'ss." + new string('F', decimalPlaces)).Format(instant));
        }
Example #26
0
 private LocalDateTime GetStartOfMonth(Instant instant) => GetStartOfMonth(instant.InUtc().LocalDateTime);
Example #27
0
 public ZonedDateTime InUtc()
 {
     return(Sample.InUtc());
 }
        private void ValidateZoneEquality(Instant instant, DateTimeZone nodaZone, TimeZoneInfo windowsZone)
        {
            // The BCL is basically broken (up to and including .NET 4.5.1 at least) around its interpretation
            // of its own data around the new year. See http://codeblog.jonskeet.uk/2014/09/30/the-mysteries-of-bcl-time-zone-data/
            // for details. We're not trying to emulate this behaviour.
            // It's a lot *better* for .NET 4.6, 
            var utc = instant.InUtc();
            if ((utc.Month == 12 && utc.Day == 31) || (utc.Month == 1 && utc.Day == 1))
            {
                return;
            }

            var interval = nodaZone.GetZoneInterval(instant);

            // Check that the zone interval really represents a transition. It could be a change in
            // wall offset, name, or the split between standard time and daylight savings for the interval.
            if (interval.RawStart != Instant.BeforeMinValue)
            {
                var previousInterval = nodaZone.GetZoneInterval(interval.Start - Duration.Epsilon);
                Assert.AreNotEqual(new {interval.WallOffset, interval.Name, interval.StandardOffset},
                    new {previousInterval.WallOffset, previousInterval.Name, previousInterval.StandardOffset},
                    "Non-transition from {0} to {1}", previousInterval, interval);
            }
            var nodaOffset = interval.WallOffset;
            var windowsOffset = windowsZone.GetUtcOffset(instant.ToDateTimeUtc());
            Assert.AreEqual(windowsOffset, nodaOffset.ToTimeSpan(), $"Incorrect offset at {instant} in interval {interval}");
            var bclDaylight = windowsZone.IsDaylightSavingTime(instant.ToDateTimeUtc());
            Assert.AreEqual(bclDaylight, interval.Savings != Offset.Zero,
                $"At {instant}, BCL IsDaylightSavingTime={bclDaylight}; Noda savings={interval.Savings}");
        }
Example #29
0
 public ZonedDateTime InUtc() => Sample.InUtc();
Example #30
0
        /// <summary>
        ///     Sets the calculation method parameters from given method preset.
        /// </summary>
        /// <param name="instant">
        ///     <see cref="Instant" /> of time.
        /// </param>
        /// <param name="preset">
        ///     <see cref="CalculationMethodPreset" /> to set.
        /// </param>
        public void SetCalculationMethodPreset(Instant instant, CalculationMethodPreset preset)
        {
            //
            // Umm Al-Qura University, Makkah
            if (preset == CalculationMethodPreset.UmmAlQuraUniversity)
            {
                // Convert Gregorian date to Hijri.
                var calendarSystem = CalendarSystem.IslamicBcl;
                var hijri          = instant.InUtc().WithCalendar(calendarSystem);
                var isBefore1430H  = hijri.Year < 1430;
                var isRamadhan     = hijri.Month == 9;

                Preset = CalculationMethodPreset.UmmAlQuraUniversity;
                FajrParameter.Value    = isBefore1430H ? 19 : 18.5;
                FajrParameter.Type     = PrayerCalculationParameterType.Angle;
                MaghribParameter.Value = 0.0;
                MaghribParameter.Type  = PrayerCalculationParameterType.MinutesAdjust;
                IshaParameter.Value    = isRamadhan ? 120.0 : 90.0;
                IshaParameter.Type     = PrayerCalculationParameterType.MinutesAdjust;
                MidnightMethod         = Midnight.Standard;
                return;
            }

            switch (preset)
            {
            case CalculationMethodPreset.IthnaAshari:
                Preset = CalculationMethodPreset.IthnaAshari;
                FajrParameter.Value    = 16.0;
                FajrParameter.Type     = PrayerCalculationParameterType.Angle;
                MaghribParameter.Value = 4.0;
                MaghribParameter.Type  = PrayerCalculationParameterType.Angle;
                IshaParameter.Value    = 14.0;
                IshaParameter.Type     = PrayerCalculationParameterType.Angle;
                MidnightMethod         = Midnight.Jafari;
                return;

            case CalculationMethodPreset.UniversityOfIslamicSciencesKarachi:
                Preset = CalculationMethodPreset.UniversityOfIslamicSciencesKarachi;
                FajrParameter.Value    = 18.0;
                FajrParameter.Type     = PrayerCalculationParameterType.Angle;
                MaghribParameter.Value = 0.0;
                MaghribParameter.Type  = PrayerCalculationParameterType.MinutesAdjust;
                IshaParameter.Value    = 18.0;
                IshaParameter.Type     = PrayerCalculationParameterType.Angle;
                MidnightMethod         = Midnight.Standard;
                return;

            case CalculationMethodPreset.IslamicSocietyOfNorthAmerica:
                Preset = CalculationMethodPreset.IslamicSocietyOfNorthAmerica;
                FajrParameter.Value    = 15.0;
                FajrParameter.Type     = PrayerCalculationParameterType.Angle;
                MaghribParameter.Value = 0.0;
                MaghribParameter.Type  = PrayerCalculationParameterType.MinutesAdjust;
                IshaParameter.Value    = 15.0;
                IshaParameter.Type     = PrayerCalculationParameterType.Angle;
                MidnightMethod         = Midnight.Standard;
                return;

            case CalculationMethodPreset.MuslimWorldLeague:
                Preset = CalculationMethodPreset.MuslimWorldLeague;
                FajrParameter.Value    = 18.0;
                FajrParameter.Type     = PrayerCalculationParameterType.Angle;
                MaghribParameter.Value = 0.0;
                MaghribParameter.Type  = PrayerCalculationParameterType.MinutesAdjust;
                IshaParameter.Value    = 17.0;
                IshaParameter.Type     = PrayerCalculationParameterType.Angle;
                MidnightMethod         = Midnight.Standard;
                return;

            case CalculationMethodPreset.EgyptianGeneralAuthorityOfSurvey:
                Preset = CalculationMethodPreset.EgyptianGeneralAuthorityOfSurvey;
                FajrParameter.Value    = 19.5;
                FajrParameter.Type     = PrayerCalculationParameterType.Angle;
                MaghribParameter.Value = 0.0;
                MaghribParameter.Type  = PrayerCalculationParameterType.MinutesAdjust;
                IshaParameter.Value    = 17.5;
                IshaParameter.Type     = PrayerCalculationParameterType.Angle;
                MidnightMethod         = Midnight.Standard;
                return;

            case CalculationMethodPreset.InstituteOfGeophysicsUniversityOfTehran:
                Preset = CalculationMethodPreset.InstituteOfGeophysicsUniversityOfTehran;
                FajrParameter.Value    = 17.7;
                FajrParameter.Type     = PrayerCalculationParameterType.Angle;
                MaghribParameter.Value = 4.5;
                MaghribParameter.Type  = PrayerCalculationParameterType.Angle;
                IshaParameter.Value    = 14.0;
                IshaParameter.Type     = PrayerCalculationParameterType.Angle;
                MidnightMethod         = Midnight.Jafari;
                return;

            case CalculationMethodPreset.UnionDesOrganisationsIslamiquesDeFrance:
                Preset = CalculationMethodPreset.UnionDesOrganisationsIslamiquesDeFrance;
                FajrParameter.Value    = 12.0;
                FajrParameter.Type     = PrayerCalculationParameterType.Angle;
                MaghribParameter.Value = 0.0;
                MaghribParameter.Type  = PrayerCalculationParameterType.MinutesAdjust;
                IshaParameter.Value    = 12.0;
                IshaParameter.Type     = PrayerCalculationParameterType.Angle;
                MidnightMethod         = Midnight.Standard;
                return;

            case CalculationMethodPreset.MajlisUgamaIslamSingapura:
                Preset = CalculationMethodPreset.MajlisUgamaIslamSingapura;
                FajrParameter.Value    = 20.0;
                FajrParameter.Type     = PrayerCalculationParameterType.Angle;
                MaghribParameter.Value = 0.0;
                MaghribParameter.Type  = PrayerCalculationParameterType.MinutesAdjust;
                IshaParameter.Value    = 18.0;
                IshaParameter.Type     = PrayerCalculationParameterType.Angle;
                MidnightMethod         = Midnight.Standard;
                return;

            case CalculationMethodPreset.DepartmentOfIslamicAdvancementOfMalaysia:
                Preset = CalculationMethodPreset.DepartmentOfIslamicAdvancementOfMalaysia;
                FajrParameter.Value    = 20.0;
                FajrParameter.Type     = PrayerCalculationParameterType.Angle;
                MaghribParameter.Value = 0.0;
                MaghribParameter.Type  = PrayerCalculationParameterType.MinutesAdjust;
                IshaParameter.Value    = 18.0;
                IshaParameter.Type     = PrayerCalculationParameterType.Angle;
                MidnightMethod         = Midnight.Standard;
                return;

            default:
                throw new ArgumentOutOfRangeException(nameof(preset));
            }
        }
        public static Serial NewSerial(Instant instant)
        {
            var utc = instant.InUtc();

            return(new Serial(utc.Year, utc.Month, utc.Day, 0));
        }