public LocalInterval Map(DateTimeZone from, DateTimeZone to)
        {
            LocalDateTime?start = Start.HasValue && from != null?from.AtLeniently(Start.Value).ToInstant().InZone(to).LocalDateTime : (LocalDateTime?)null;

            LocalDateTime?end = End.HasValue && to != null?from.AtLeniently(End.Value).ToInstant().InZone(to).LocalDateTime : (LocalDateTime?)null;

            return(new LocalInterval(start, end, Payload, Name));
        }
        public void AtLeniently_AmbiguousTime_ReturnsLaterMapping()
        {
            var local = new LocalDateTime(2009, 11, 1, 1, 30, 0);
            var zoned = Pacific.AtLeniently(local);

            Assert.AreEqual(local, zoned.LocalDateTime);
            Assert.AreEqual(Offset.FromHours(-8), zoned.Offset);
        }
예제 #3
0
        public void InZone()
        {
            // Don't need much for this - it only delegates.
            var ambiguous = new LocalDateTime(2009, 11, 1, 1, 30, 0);
            var skipped   = new LocalDateTime(2009, 3, 8, 2, 30, 0);

            Assert.AreEqual(Pacific.AtLeniently(ambiguous), ambiguous.InZone(Pacific, Resolvers.LenientResolver));
            Assert.AreEqual(Pacific.AtLeniently(skipped), skipped.InZone(Pacific, Resolvers.LenientResolver));
        }
        /// <summary>
        /// Maps the <see cref="DateTimeInterval"/> leniently to the given time zone.
        /// </summary>
        /// <returns>The <see cref="Interval"/> that was leniently mapping for the given time zone.</returns>
        public static Interval InZone(this DateTimeInterval dateTimeInterval, DateTimeZone timeZone)
        {
            if (dateTimeInterval == null)
            {
                throw new System.ArgumentNullException(nameof(dateTimeInterval));
            }
            if (timeZone == null)
            {
                throw new System.ArgumentNullException(nameof(timeZone));
            }

            var start = timeZone.AtLeniently(dateTimeInterval.Start).ToInstant();
            var end   = timeZone.AtLeniently(dateTimeInterval.End).ToInstant();

            return(new Interval(start, end));
        }
예제 #5
0
        private OneOffSchedule(
            [CanBeNull] string name,
            DateTime dateTime,
            [NotNull] string timeZone,
            ScheduleOptions options = ScheduleOptions.None)
        {
            if (timeZone == null)
            {
                throw new ArgumentNullException("timeZone");
            }

            DateTimeZone tz = TimeHelpers.DateTimeZoneProvider[timeZone];

            if (tz == null)
            {
                throw new ArgumentException(
                          // ReSharper disable once AssignNullToNotNullAttribute
                          string.Format(Resource.OneOffSchedule_InvalidTimeZone, timeZone),
                          "timeZone");
            }

            _name    = name;
            Instant  = tz.AtLeniently(LocalDateTime.FromDateTime(dateTime)).ToInstant();
            _options = options;
        }
예제 #6
0
        /// <summary>
        /// Maps the given <see cref="DateTimeInterval"/> to the corresponding <see cref="Interval"/> in the given time zone in a lenient manner:
        /// ambiguous values map to the earlier of the alternatives, and "skipped" values are shifted forward by the duration of the "gap".
        /// </summary>
        /// <param name="timeZone">The time zone.</param>
        /// <param name="dateTimeInterval">The date/time interval.</param>
        /// <returns>The <see cref="Interval"/> corresponding to the given date/time interval in the given time zone.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="timeZone"/> or <paramref name="dateTimeInterval"/> is <c>null</c>.</exception>
        public static Interval AtLeniently(this DateTimeZone timeZone, DateTimeInterval dateTimeInterval)
        {
            if (timeZone == null)
            {
                throw new ArgumentNullException(nameof(timeZone));
            }

            if (dateTimeInterval == null)
            {
                throw new ArgumentNullException(nameof(dateTimeInterval));
            }

            return(new Interval(
                       timeZone.AtLeniently(dateTimeInterval.Start).ToInstant(),
                       timeZone.AtLeniently(dateTimeInterval.End).ToInstant()
                       ));
        }
예제 #7
0
 /// <summary>
 /// Converts the specified time from the <paramref name="from"/> time zone to <see cref="TimeZones.Utc"/>
 /// </summary>
 /// <param name="time">The time to be converted in terms of the <paramref name="from"/> time zone</param>
 /// <param name="from">The time zone the specified <paramref name="time"/> is in</param>
 /// <param name="strict">True for strict conversion, this will throw during ambiguitities, false for lenient conversion</param>
 /// <returns>The time in terms of the to time zone</returns>
 public static DateTime ConvertToUtc(this DateTime time, DateTimeZone from, bool strict = false)
 {
     if (strict)
     {
         return(from.AtStrictly(LocalDateTime.FromDateTime(time)).ToDateTimeUtc());
     }
     return(from.AtLeniently(LocalDateTime.FromDateTime(time)).ToDateTimeUtc());
 }
        /// <summary>
        /// Formats the value of the DFP date time using the specified
        /// <see href="https://nodatime.org/2.3.x/userguide/localdatetime-patterns">
        /// NodaTime compatible</see> format.
        /// </summary>
        public static string ToString(AdManagerDateTime dateTime, string patternText,
                                      IFormatProvider formatProvider)
        {
            LocalDateTime localDateTime = new LocalDateTime(dateTime.date.year, dateTime.date.month,
                                                            dateTime.date.day, dateTime.hour, dateTime.minute, dateTime.second);
            DateTimeZone timeZone = DateTimeZoneProviders.Tzdb[dateTime.timeZoneId];

            return(timeZone.AtLeniently(localDateTime).ToString(patternText, formatProvider));
        }
예제 #9
0
        /// <summary>
        /// Converts the specified time from the <paramref name="from"/> time zone to the <paramref name="to"/> time zone
        /// </summary>
        /// <param name="time">The time to be converted in terms of the <paramref name="from"/> time zone</param>
        /// <param name="from">The time zone the specified <paramref name="time"/> is in</param>
        /// <param name="to">The time zone to be converted to</param>
        /// <param name="strict">True for strict conversion, this will throw during ambiguitities, false for lenient conversion</param>
        /// <returns>The time in terms of the to time zone</returns>
        public static DateTime ConvertTo(this DateTime time, DateTimeZone from, DateTimeZone to, bool strict = false)
        {
            if (strict)
            {
                return(from.AtStrictly(LocalDateTime.FromDateTime(time)).WithZone(to).ToDateTimeUnspecified());
            }

            return(from.AtLeniently(LocalDateTime.FromDateTime(time)).WithZone(to).ToDateTimeUnspecified());
        }
        /// <summary>
        /// Apply DateTimeZone leniently
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="dateTimeZone"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        public static DateTimeOffset ApplyDateTimeZoneLeniently(this DateTime dt, DateTimeZone dateTimeZone)
        {
            if (dateTimeZone == null)
            {
                throw new ArgumentNullException(nameof(dateTimeZone));
            }
            var local = dt.ToLocalDateTime();

            return(dateTimeZone.AtLeniently(local).ToDateTimeOffset());
        }
예제 #11
0
        public static DateTime FromTimezoneToUtc(this DateTime dateTime, DateTimeZone timezone)
        {
            EnsureArg.IsNotNull(timezone);

            LocalDateTime localDateTime = LocalDateTime.FromDateTime(dateTime);

            var zonedDbDateTime = timezone.AtLeniently(localDateTime);

            return(zonedDbDateTime.ToDateTimeUtc());
        }
예제 #12
0
        /// <summary>
        /// Round down a given zoned datetime to the nearest time of emission.
        /// </summary>
        /// <param name="zonedBarTime">The zoned bar datetime to be rounded down.</param>
        /// <returns>The rounded down and zoned bar time (TZ: <see cref="CloseTimeZone"/>).</returns>
        protected ZonedDateTime RoundDownToLastEmitTime(ZonedDateTime zonedBarTime)
        {
            // Convert time given to the same timezone as the close specified if it isn't already
            var zonedConvertedBarTimeDT = zonedBarTime.WithZone(CloseTimeZone);

            // Get timezoned close (now that we have a date)
            var zonedDailyCloseDT = CloseTimeZone.AtLeniently(zonedConvertedBarTimeDT.Date + DailyCloseTime);

            // Return the last close, zoned into the close timezone
            return(zonedConvertedBarTimeDT.TimeOfDay >= zonedDailyCloseDT.TimeOfDay ? zonedDailyCloseDT : zonedDailyCloseDT - Duration.FromStandardDays(1));
        }
예제 #13
0
        /// <summary>
        /// Returns the given user local time, converted to UTC.
        /// </summary>
        public DateTime ToUtcTime(DateTime userLocalTime)
        {
            if (userLocalTime == DateTime.MinValue)
            {
                return(DateTime.MinValue);
            }

            return(LocalTimeZone
                   .AtLeniently(LocalDateTime.FromDateTime(userLocalTime))
                   .ToDateTimeUtc());
        }
        public static DateTime ConvertToUtcFromTimeZone(this DateTime dateTime, DateTimeZone timeZone)
        {
            timeZone.ThrowIfNull("timeZone");

            if (dateTime.Kind == DateTimeKind.Utc)
            {
                return(dateTime);
            }

            return(timeZone.AtLeniently(LocalDateTime.FromDateTime(dateTime)).WithZone(DateTimeZone.Utc).ToDateTimeUtc());
        }
        /// <summary>
        /// Adds the days taking into account DST.
        /// </summary>
        /// <param name="targetUtc">The target UTC.</param>
        /// <param name="timeZone">The time zone.</param>
        /// <param name="numberOfDays">The number of days.</param>
        /// <returns></returns>
        private DateTime AddDays(DateTime targetUtc, string timeZone, int numberOfDays)
        {
            Instant instant = Instant.FromDateTimeUtc(targetUtc);

            DateTimeZone timeZoneInfo = DateTimeZoneProviders.Tzdb[timeZone];

            ZonedDateTime zoned = instant.InZone(timeZoneInfo);

            LocalDateTime updated = zoned.LocalDateTime.PlusDays(numberOfDays); // Adding a number of days

            ZonedDateTime updatedZoned = timeZoneInfo.AtLeniently(updated);

            return(updatedZoned.ToDateTimeUtc());
        }
예제 #16
0
        /// <summary>
        /// Updates consolidator only at a fixed time of day in a specific timezone.
        /// </summary>
        /// <param name="data">The new data for the consolidator.</param>
        public override void Update(T data)
        {
            // If we have new data, aggregate it onto the working bar
            if (data.Time >= _lastEmit)
            {
                AggregateBar(ref _workingBar, data);
            }

            // Data and working bar are in exchange TZ, let's zone them
            var zonedDataEndTimeDT    = ExchangeTimeZone.AtLeniently(CreateLocalDateTime(data.EndTime));
            var zonedWorkingBarTimeDT = ExchangeTimeZone.AtLeniently(CreateLocalDateTime(_workingBar.Time));

            // The last time we should have emitted at, with respect to the end of the incoming data
            var shouldHaveEmittedAt = RoundDownToLastEmitTime(zonedDataEndTimeDT);

            /// We consolidate if the following condition(s) are met:
            ///		1. Incoming bar's end time (<see cref="ZonedDateTime"/>) is same as the
            ///		time we should have emitted at.
            ///		2. The time we should have emitted at is after the current working bar's
            ///		start time.
            if (InexactCompareTo(zonedDataEndTimeDT, shouldHaveEmittedAt) == 0 &&
                InexactCompareTo(shouldHaveEmittedAt, zonedWorkingBarTimeDT) > 0)
            {
                // Set the EndTime accordingly
                var workingTradeBar = _workingBar as QuoteBar;
                workingTradeBar.EndTime = shouldHaveEmittedAt.WithZone(ExchangeTimeZone).ToDateTimeUnspecified();

                // Fire consolidation event
                OnDataConsolidated(_workingBar);

                // Last emission was when this bar ended
                _lastEmit = _workingBar.EndTime;

                // Reset the working bar
                _workingBar = null;
            }
        }
예제 #17
0
        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);
        }
예제 #18
0
        /// <summary>
        /// Get the start or end date time in UTC for the specified date range type in the specified time zone.
        /// </summary>
        /// <param name="dateRangeType">The date range type (today, current week etc.)</param>
        /// <param name="ianaTimeZoneName">The IANA time zone name</param>
        /// <param name="isStart">True for start and false for end of date range</param>
        /// <param name="useEndOfCurrentDay">Flag to indicate if end of current periods are now or the end of the current day</param>
        /// <returns>The start or end UTC for the range in the time zone</returns>
        public static DateTime?UtcForDateRangeType(this DateRangeType dateRangeType, string ianaTimeZoneName, bool isStart, bool useEndOfCurrentDay = false)
        {
            if (dateRangeType == DateRangeType.Custom || dateRangeType == DateRangeType.ProjectExtents || string.IsNullOrEmpty(ianaTimeZoneName))
            {
                return(null);
            }

            DateTimeZone  timeZone = DateTimeZoneProviders.Tzdb[ianaTimeZoneName];
            ZonedClock    clock    = SystemClock.Instance.InZone(timeZone);
            LocalDateTime localNow = clock.GetCurrentLocalDateTime();
            var           local    = localNow.LocalDateTimeForDateRangeType(dateRangeType, isStart);
            var           zoned    = timeZone.AtLeniently(local);

            return(zoned.ToDateTimeUtc());
        }
        /// <summary>
        /// Converts the time to UTC (using IANA (Olson) timezone).
        /// </summary>
        /// <param name="local">The local.</param>
        /// <param name="timezone">IANA (Olson) timezone.</param>
        /// <returns></returns>
        public static DateTime ConvertTimeToUtc(this DateTime local, string timezone)
        {
            if (string.IsNullOrEmpty(timezone))
            {
                throw new ArgumentException(nameof(timezone));
            }

            string tz = DateTimeZoneProviders.Tzdb.Ids.FirstOrDefault(e => e.ToLower() == timezone.ToLower());

            if (string.IsNullOrEmpty(tz))
            {
                throw new ArgumentException(nameof(timezone));
            }

            LocalDateTime localDateTime = LocalDateTime.FromDateTime(local);

            DateTimeZone timezoneInfo = DateTimeZoneProviders.Tzdb[tz];

            ZonedDateTime zoned = timezoneInfo.AtLeniently(localDateTime);

            return(zoned.ToDateTimeUtc());
        }
예제 #20
0
 /// <summary>
 /// Converts from client time to UTC.
 /// </summary>
 /// <param name="timeZone">Client time zone.</param>
 /// <param name="clientTime">Client time.</param>
 /// <returns></returns>
 public DateTime FromClientTime(DateTimeZone timeZone, DateTime clientTime)
 {
     return(timeZone.AtLeniently(LocalDateTime.FromDateTime(clientTime)).ToDateTimeUtc());
 }
예제 #21
0
        public TestClock(string time, DateTimeZone zone)
        {
            ParseResult <LocalDateTime> result = LocalDateTimePattern.GeneralIso.Parse(time);

            CurrentInstant = zone.AtLeniently(result.Value).ToInstant();
        }
예제 #22
0
 /// <summary>
 /// Maps two <see cref="LocalDateTime"/>s to the corresponding <see cref="Interval"/> in the given time zone.
 /// </summary>
 /// <param name="timeZone">The time zone.</param>
 /// <param name="startLocalDateTime">The date/time mapped to the start of the interval.</param>
 /// <param name="endLocalDateTime">The date/time mapped to the end of the interval.</param>
 /// <returns></returns>
 public static Interval AtInterval(this DateTimeZone timeZone, LocalDateTime startLocalDateTime, LocalDateTime endLocalDateTime) => new Interval(
     timeZone.AtLeniently(startLocalDateTime).ToInstant(),
     timeZone.AtLeniently(endLocalDateTime).ToInstant()
     );
예제 #23
0
 private static DateTime LocalDateTimeToDateTime(LocalDateTime ldt, DateTimeZone tz, bool justDate) => justDate?ldt.Date.ToDateTimeUnspecified() : tz.AtLeniently(ldt).ToDateTimeUtc();
예제 #24
0
        public static Instant NextValid(
            this Instant instant,
            Month month     = Month.Every,
            Week week       = Week.Every,
            Day day         = Day.Every,
            WeekDay weekDay = WeekDay.Every,
            Hour hour       = Hour.Zeroth,
            Minute minute   = Minute.Zeroth,
            Second second   = Second.Zeroth,
            [CanBeNull] CalendarSystem calendarSystem = null,
            [CanBeNull] DateTimeZone timeZone         = null)
        {
            // Never case, if any are set to never, we'll never get a valid date.
            if ((month == Month.Never) ||
                (week == Week.Never) ||
                (day == Day.Never) ||
                (weekDay == WeekDay.Never) ||
                (hour == Hour.Never) ||
                (minute == Minute.Never) ||
                (second == Second.Never))
            {
                return(Instant.MaxValue);
            }

            if (calendarSystem == null)
            {
                calendarSystem = CalendarSystem.Iso;
            }
            if (timeZone == null)
            {
                timeZone = DateTimeZone.Utc;
            }
            Debug.Assert(calendarSystem != null);
            Debug.Assert(timeZone != null);

            // Move to next second.
            instant = instant.CeilingSecond();

            // Every second case.
            if ((month == Month.Every) &&
                (day == Day.Every) &&
                (weekDay == WeekDay.Every) &&
                (hour == Hour.Every) &&
                (minute == Minute.Every) &&
                (second == Second.Every) &&
                (week == Week.Every))
            {
                return(instant);
            }

            // Get days and months.
            int[] days   = Days(day).OrderBy(dy => dy).ToArray();
            int[] months = month.Months().ToArray();

            // Remove months where the first day isn't in the month.
            int firstDay = days.First();

            if (firstDay > 28)
            {
                // 2000 is a leap year, so February has 29 days.
                months = months.Where(mn => calendarSystem.GetDaysInMonth(2000, mn) >= firstDay).ToArray();
                if (months.Length < 1)
                {
                    return(Instant.MaxValue);
                }
            }

            // Get zoned date time.
            ZonedDateTime zdt = new ZonedDateTime(instant, timeZone, calendarSystem);
            int           y   = zdt.Year;
            int           m   = zdt.Month;
            int           d   = zdt.Day;
            int           h   = zdt.Hour;
            int           n   = zdt.Minute;
            int           s   = zdt.Second;

            int[] weeks = week.Weeks().ToArray();

            IsoDayOfWeek[] weekDays = weekDay.WeekDays().ToArray();
            int[]          hours    = hour.Hours().OrderBy(i => i).ToArray();
            int[]          minutes  = minute.Minutes().OrderBy(i => i).ToArray();
            int[]          seconds  = second.Seconds().ToArray();

            do
            {
                foreach (int currentMonth in months)
                {
                    if (currentMonth < m)
                    {
                        continue;
                    }
                    if (currentMonth > m)
                    {
                        d = 1;
                        h = n = s = 0;
                    }
                    m = currentMonth;
                    foreach (int currentDay in days)
                    {
                        if (currentDay < d)
                        {
                            continue;
                        }
                        if (currentDay > d)
                        {
                            h = n = s = 0;
                        }
                        d = currentDay;

                        // Check day is valid for this month.
                        if (d > calendarSystem.GetDaysInMonth(y, m))
                        {
                            break;
                        }

                        // We have a potential day, check week and week day
                        zdt = timeZone.AtLeniently(new LocalDateTime(y, m, d, h, n, s, calendarSystem));
                        if ((week != Week.Every) &&
                            (!weeks.Contains(zdt.WeekOfWeekYear)))
                        {
                            continue;
                        }
                        if ((weekDay != WeekDay.Every) &&
                            (!weekDays.Contains(zdt.IsoDayOfWeek)))
                        {
                            continue;
                        }

                        // We have a date match, check time.
                        foreach (int currentHour in hours)
                        {
                            if (currentHour < h)
                            {
                                continue;
                            }
                            if (currentHour > h)
                            {
                                n = s = 0;
                            }
                            h = currentHour;
                            foreach (int currentMinute in minutes)
                            {
                                if (currentMinute < n)
                                {
                                    continue;
                                }
                                if (currentMinute > n)
                                {
                                    s = 0;
                                }
                                n = currentMinute;
                                foreach (int currentSecond in seconds)
                                {
                                    if (currentSecond < s)
                                    {
                                        continue;
                                    }
                                    return
                                        (timeZone.AtLeniently(
                                             new LocalDateTime(y, m, d, h, n, currentSecond, calendarSystem)).ToInstant());
                                }
                                n = s = 0;
                            }
                            h = n = s = 0;
                        }
                        d = 1;
                    }
                    d = 1;
                    h = n = s = 0;
                }
                y++;

                // Don't bother checking max year.
                if (y >= calendarSystem.MaxYear)
                {
                    return(Instant.MaxValue);
                }

                // Start next year
                m = d = 1;
                h = n = s = 0;
            } while (true);
        }