Beispiel #1
0
        private void CreateStreamSessions(ScheduledStream stream, DateTimeZone timeZone)
        {
            ZonedClock zonedClock = _clock.InZone(timeZone);

            LocalDate nextOfDay = zonedClock.GetCurrentDate()
                                  .With(DateAdjusters.Next(stream.DayOfWeek));

            for (int i = 0; i < 52; i++)
            {
                LocalDateTime nextLocalStartDateTime = nextOfDay + stream.LocalStartTime;
                LocalDateTime nextLocalEndDateTime   = nextOfDay + stream.LocalEndTime;

                var streamSession = new StreamSession
                {
                    TzdbVersionId = DateTimeZoneProviders.Tzdb.VersionId,
                    UtcStartTime  = nextLocalStartDateTime
                                    .InZoneLeniently(timeZone)
                                    .ToInstant(),
                    UtcEndTime = nextLocalEndDateTime.InZoneLeniently(timeZone).ToInstant(),
                };

                stream.Sessions.Add(streamSession);

                nextOfDay = nextOfDay.PlusWeeks(1);
            }
        }
        public void RoundNearest(LocalDateTime origin, Duration interval, LocalDateTime expected)
        {
            var zonedOrigin = origin.InZoneLeniently(Timezone);
            var rounded     = zonedOrigin.RoundNearest(interval);

            Assert.Equal(expected.InZoneLeniently(Timezone), rounded);
        }
Beispiel #3
0
        public void InZoneLeniently_AmbiguousTime_ReturnsEarlierMapping()
        {
            var local = new LocalDateTime(2009, 11, 1, 1, 30, 0);
            var zoned = local.InZoneLeniently(Pacific);

            Assert.AreEqual(local, zoned.LocalDateTime);
            Assert.AreEqual(Offset.FromHours(-7), zoned.Offset);
        }
Beispiel #4
0
        public void InZoneLeniently_ReturnsStartOfSecondInterval()
        {
            var local = new LocalDateTime(2009, 3, 8, 2, 30, 0);
            var zoned = local.InZoneLeniently(Pacific);

            Assert.AreEqual(new LocalDateTime(2009, 3, 8, 3, 30, 0), zoned.LocalDateTime);
            Assert.AreEqual(Offset.FromHours(-7), zoned.Offset);
        }
Beispiel #5
0
        private static ZonedDateTime GetZonedTime(LocalDateTime localTime, string timeZoneId)
        {
            // здесь используется не windows-specific словарь идентификаторов, а более "принятый" сообществом
            var timeZone = TzdbDateTimeZoneSource.Default.ForId(timeZoneId);

            // обрати внимание, есть два метода, превращающих локальное время + часовой пояс в ZonedDateTime: InZoneLeniently и InZoneStrictly. Первый не ругается на сомнительное локальное время, второй - бросает исключение. Для наглядности конкретно этого примера я использовал "снисходительный" вариант.
            return(localTime.InZoneLeniently(timeZone));
        }
Beispiel #6
0
        public static DateTimeClass New(MondValue _,
                                        int year, int month = 1, int day    = 1,
                                        int hour            = 0, int minute = 0, int second = 0, int millisecond = 0,
                                        string timeZone     = null)
        {
            var local = new LocalDateTime(year, month, day, hour, minute, second, millisecond);

            return(new DateTimeClass(local.InZoneLeniently(DateTimeHelper.Find(timeZone))));
        }
    static void Main()
    {
        var local = new LocalDateTime(2014, 3, 30, 2, 30, 0);
        var zone  = DateTimeZoneProviders.Tzdb["Europe/Paris"];

        var zoned = local.InZoneLeniently(zone);

        Console.WriteLine(zoned);      // 2014-03-30T03:00:00 Europe/Paris (+02)
    }
        public void Construct_FromLocal_ValidLaterOffset()
        {
            SingleTransitionDateTimeZone zone = new SingleTransitionDateTimeZone(Instant.FromUtc(2011, 6, 12, 22, 0), 4, 3);

            LocalDateTime local = new LocalDateTime(2011, 6, 13, 1, 30);
            ZonedDateTime zoned = new ZonedDateTime(local, zone, zone.LateInterval.WallOffset);

            // Leniently will return the later instant
            Assert.AreEqual(zoned, local.InZoneLeniently(zone));
        }
Beispiel #9
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());
        }
Beispiel #10
0
        /// <summary>
        /// Converts a DateTime into a DateTimeOffset for the specified IANA time zone name.
        /// </summary>
        /// <param name="dateTime">A date time to convert.</param>
        /// <param name="timeZone">A IANA time zone name.</param>
        /// <returns>A new date time offset.</returns>
        public static DateTimeOffset ToDateTimeOffset(this DateTime dateTime, string timeZone)
        {
            Throw.IfArgumentNullOrWhitespace(timeZone, nameof(timeZone));

            DateTimeZone  dateTimeZone = DateTimeZoneProviders.Tzdb[timeZone];
            LocalDateTime local        = LocalDateTime.FromDateTime(dateTime);

            // The lenient method will automatically handle conflicting edge-cases such as daylight savings.
            // The alternative is to use strict which will instead throw an exception in such edge-cases.
            return(local.InZoneLeniently(dateTimeZone).ToDateTimeOffset());
        }
        public static Instant ToInstant(this LocalDateTime local, IDateTimeZoneProvider provider, string timeZoneId)
        {
            var timeZone = provider.GetZoneOrNull(timeZoneId);

            if (timeZone is null)
            {
                throw new ArgumentException(nameof(timeZoneId));
            }

            return(local.InZoneLeniently(timeZone).ToInstant());
        }
Beispiel #12
0
        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));
        }
Beispiel #13
0
        /*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());
        }
Beispiel #14
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 ZonedDateTime InZone(this DateTime dateTime, DateTimeZone zone)
        {
            if (dateTime.Kind == DateTimeKind.Local)
            {
                throw new ArgumentException("Expected non-local kind of DateTime");
            }

            LocalDateTime asLocal = dateTime.ToLocalDateTime();
            ZonedDateTime asZoned = asLocal.InZoneLeniently(zone);

            return(asZoned);
        }
Beispiel #15
0
        public static DateTimeOffset GetLocalDateTimeOffset(this GeoPoint geoPoint, DateTime dateTime)
        {
            if (geoPoint == null || Math.Abs(geoPoint.Latitude) < .0001)
            {
                return(dateTime);
            }

            var timeZone = GetTimeZone(geoPoint);
            var ldt      = new LocalDateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second);
            var zdt      = ldt.InZoneLeniently(DateTimeZoneProviders.Tzdb[timeZone]);

            return(zdt.ToDateTimeOffset());
        }
Beispiel #16
0
        public void ChicagoIndependanceDay()
        {
            const string dateTime = "2017-07-04 20:30:40";
            const string timeZone = "America/Chicago";
            var          d        = DateTime.Parse(dateTime);

            var ldt  = new LocalDateTime(d.Year, d.Month, d.Day, d.Hour, d.Minute, d.Second);
            var zdt  = ldt.InZoneLeniently(DateTimeZoneProviders.Tzdb[timeZone]);
            var date = zdt.ToDateTimeOffset();

            date.ShouldBeEquivalentTo(new DateTimeOffset(2017, 07, 04, 20, 30, 40, TimeSpan.FromHours(-5)));
            Console.WriteLine(date.ToString("s"));
        }
        private static ZonedDateTime GetZonedDateTime(int year, int month, int day, int hour, int minute, int second, string timeZoneId, bool inZoneLeniantly)
        {
            var localDateTime = new LocalDateTime(year, month, day, hour, minute, second);

            if (inZoneLeniantly)
            {
                return(localDateTime.InZoneLeniently(DateTimeZoneProviders.Tzdb[timeZoneId]));
            }

            else
            {
                return(localDateTime.InZoneStrictly(DateTimeZoneProviders.Tzdb[timeZoneId]));
            }
        }
Beispiel #18
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());
        }
Beispiel #19
0
 /// <summary>
 /// Convert LocalDateTime in the specified timezone to Instant.
 ///
 /// Converts LocalDateTimeUtil.Empty to InstantUtil.Empty.
 ///
 /// Use timeZone = DateTimeZone.Utc for the UTC timezone.
 /// </summary>
 public static Instant ToInstant(this LocalDateTime value, DateTimeZone timeZone)
 {
     if (value == LocalDateTimeUtil.Empty)
     {
         return(InstantUtil.Empty);
     }
     else
     {
         // Use lenient conversion to avoid an error when during
         // the daylight savings time clock change the same local
         // datetime repeats twice. In this case the earlier of
         // the alternatives will be used.
         return(value.InZoneLeniently(timeZone).ToInstant());
     }
 }
Beispiel #20
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);
    }
Beispiel #21
0
        public void FortWayneIndependanceDay()
        {
            const string dateTime     = "2017-07-04 20:30:40";
            var          timeZone     = TimeZoneLookup.GetTimeZone(40.977506, -85.196059).Result;
            var          d            = DateTime.Parse(dateTime);
            var          abbreviation = TZNames.GetAbbreviationsForTimeZone(timeZone, "en-US").Generic;

            abbreviation.Should().Be("ET");

            var ldt  = new LocalDateTime(d.Year, d.Month, d.Day, d.Hour, d.Minute, d.Second);
            var zdt  = ldt.InZoneLeniently(DateTimeZoneProviders.Tzdb[timeZone]);
            var date = zdt.ToDateTimeOffset();

            date.ShouldBeEquivalentTo(new DateTimeOffset(2017, 07, 04, 20, 30, 40, TimeSpan.FromHours(-4)));
            Console.WriteLine(date.ToString("s"));
        }
Beispiel #22
0
        public void CuriousSubtraction()
        {
            var shanghai      = DateTimeZoneProviders.Tzdb["Asia/Shanghai"];
            var localBefore   = new LocalDateTime(1927, 12, 31, 23, 54, 02);
            var localAfter    = localBefore.PlusSeconds(1);
            var instantBefore = localBefore.InZoneLeniently(shanghai).ToInstant();
            var instantAfter  = localAfter.InZoneLeniently(shanghai).ToInstant();

            Assert.AreEqual(Duration.FromSeconds(358), instantAfter - instantBefore);

            // Now let's resolve them differently...
            var resolver = Resolvers.CreateMappingResolver(Resolvers.ReturnEarlier, Resolvers.ThrowWhenSkipped);

            instantBefore = localBefore.InZone(shanghai, resolver).ToInstant();
            instantAfter  = localAfter.InZone(shanghai, resolver).ToInstant();
            Assert.AreEqual(Duration.FromSeconds(1), instantAfter - instantBefore);
        }
Beispiel #23
0
        private DateTime WindowsTimeZone(EventDateTime time)
        {
            DateTime theDate = time.DateTime ?? DateTime.Parse(time.Date);

            if (time.TimeZone == null)
            {
                return(theDate);
            }

            LocalDateTime local     = new LocalDateTime(theDate.Year, theDate.Month, theDate.Day, theDate.Hour, theDate.Minute);
            DateTimeZone  zone      = DateTimeZoneProviders.Tzdb[TimezoneDB.FixAlexa(time.TimeZone)];
            ZonedDateTime zonedTime = local.InZoneLeniently(zone);
            DateTime      zonedUTC  = zonedTime.ToDateTimeUtc();

            log.Fine("IANA Timezone \"" + time.TimeZone + "\" mapped to \"" + zone.Id.ToString() + "\" with a UTC of " + zonedUTC.ToString("dd/MM/yyyy HH:mm:ss"));
            return(zonedUTC);
        }
Beispiel #24
0
        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);
        }
Beispiel #25
0
        public void TucsonIndependanceDay()
        {
            const string dateTime     = "2017-07-04 20:30:40";
            var          timeZone     = TimeZoneLookup.GetTimeZone(32.114510, -110.939259).Result;
            var          d            = DateTime.Parse(dateTime);
            var          abbreviation = TZNames.GetAbbreviationsForTimeZone(timeZone, "en-US").Generic;

            abbreviation.Should().Be("MT");

            var ldt  = new LocalDateTime(d.Year, d.Month, d.Day, d.Hour, d.Minute, d.Second);
            var zdt  = ldt.InZoneLeniently(DateTimeZoneProviders.Tzdb[timeZone]);
            var date = zdt.ToDateTimeOffset();

            date.ShouldBeEquivalentTo(new DateTimeOffset(2017, 07, 04, 20, 30, 40, TimeSpan.FromHours(-7)));
            var s = date.ToString("yyyy-MM-ddTHH\\:mm\\:sszzz");

            Console.WriteLine(s);
            s.Should().Be("2017-07-04T20:30:40-07:00");
        }
Beispiel #26
0
        /// <summary>
        /// Converts the date time to  UTC time
        /// </summary>
        /// <param name="dt">The date time to convert</param>
        /// <returns>The UTC date time</returns>
        public DateTime Convert(DateTime dt)
        {
            // Fork this method into the use of the current culture to do the utc conversion
            if (UseCurrentCulture)
            {
                CultureInfo currentCulture = CultureInfo.CurrentUICulture;
                RegionInfo  regionInfo     = new RegionInfo(currentCulture.Name);

                IEnumerable <string> zoneIds = NodaTime.TimeZones.TzdbDateTimeZoneSource.Default.ZoneLocations
                                               .Where(x => string.Compare(x.CountryCode, regionInfo.TwoLetterISORegionName, StringComparison.OrdinalIgnoreCase) == 0)
                                               .Select(x => x.ZoneId);

                if (!zoneIds.Any())
                {
                    return(dt);
                }

                DateTime dateTime        = DateTime.SpecifyKind(dt, DateTimeKind.Utc);
                Instant  dateTimeInstant = Instant.FromDateTimeUtc(dateTime);

                DateTimeZone  timeZone      = DateTimeZoneProviders.Tzdb[zoneIds.FirstOrDefault()];
                ZonedDateTime zonedDateTime = dateTimeInstant.InZone(timeZone);

                DateTime localDateTime = zonedDateTime.ToDateTimeUnspecified();
                return(localDateTime);
            }
            else
            {
                // Get local DateTime instance into a LocalDateTime object
                LocalDateTime localDateTime = new LocalDateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute);

                // Get the users' time zone
                IDateTimeZoneProvider timeZoneProvider = DateTimeZoneProviders.Tzdb;
                DateTimeZone          usersTimezone    = timeZoneProvider[TimeZone];

                // Format the local DateTime instance with the time zones
                ZonedDateTime zonedDbDateTime = localDateTime.InZoneLeniently(usersTimezone);

                // At this point we have all information to convert to UTC: release the kraken!
                return(zonedDbDateTime.ToDateTimeUtc());
            }
        }
 public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
 {
     if (value is string)
     {
         try
         {
             DateTime parsed = DateTime.Parse((string)value);
             LocalDateTime dt = LocalDateTime.FromDateTime(parsed);
             Instant i = dt.InZoneLeniently(DateTimeZoneProviders.Default.GetSystemDefault()).ToInstant();
             return i;
         }
         catch
         {
             throw new ArgumentException("Cannot convert '" + (string)value + "' to Instant.");
         }
     }
     else
     {
         return base.ConvertFrom(context, culture, value);
     }
 }
        public async Task<IActionResult> OnPostAsync(int channelId)
        {
            ScheduledStream stream = StreamTime.ToModel();

            var channel = await _context.Channels
                .Include(x => x.ScheduledStreams)
                .SingleAsync(x => x.Id == channelId);

            channel.ScheduledStreams.Add(stream);

            var zone = DateTimeZoneProviders.Tzdb[channel.TimeZoneId];
            var version = DateTimeZoneProviders.Tzdb.VersionId;
            ZonedClock zonedClock = _clock.InZone(zone);

            LocalDate today = zonedClock.GetCurrentDate();
            LocalDate next = today.With(DateAdjusters.Next(stream.DayOfWeek));

            
            for (int i = 0; i < 52; i++)
            {
                LocalDateTime nextLocalStartDateTime = next + stream.LocalStartTime;
                LocalDateTime nextLocalEndDateTime = next + stream.LocalEndTime;

                var streamSession = new StreamSession
                {
                    TzdbVersionId = version,
                    UtcStartTime = nextLocalStartDateTime.InZoneLeniently(zone).ToInstant(),
                    UtcEndTime = nextLocalEndDateTime.InZoneLeniently(zone).ToInstant(),
                };

                stream.Sessions.Add(streamSession);

                next = next.PlusWeeks(1);
            }

            await _context.SaveChangesAsync();

            return RedirectToPage("./Index");

        }
Beispiel #29
0
        private void cmbTimeZone_SelectedIndexChanged(object sender, EventArgs e)
        {
            timeZone = DateTimeZoneProviders.Tzdb[cmbTimeZone.SelectedItem.ToString()];
            updateFormattedDatetime();
            //Convert from a DateTime selection (assuming it is local time) back to Instant for db storage
            //Create a LocalTime using DateTime.Now
            LocalDateTime localDateTime = LocalDateTime.FromDateTime(DateTime.Now);
            ZonedDateTime zonedDateTime = localDateTime.InZoneLeniently(timeZone);
            Instant       instant       = zonedDateTime.ToInstant();

            txtTimeZoneInfo.Clear();
            txtTimeZoneInfo.Text  = "DateTime.Now: " + DateTime.Now.ToString();
            txtTimeZoneInfo.Text += Environment.NewLine;
            txtTimeZoneInfo.Text += Environment.NewLine + "Local Date Time: " + localDateTime.ToString();
            txtTimeZoneInfo.Text += Environment.NewLine + " - LocalDateTime localDateTime = LocalDateTime.FromDateTime(DateTime.Now);";
            txtTimeZoneInfo.Text += Environment.NewLine;
            txtTimeZoneInfo.Text += Environment.NewLine + "Zoned Date Time: " + zonedDateTime.ToString();
            txtTimeZoneInfo.Text += Environment.NewLine + " - ZonedDateTime zonedDateTime = localDateTime.InZoneLeniently(timeZone);";
            txtTimeZoneInfo.Text += Environment.NewLine;
            txtTimeZoneInfo.Text += Environment.NewLine + "Instant: " + instant.ToString();
            txtTimeZoneInfo.Text += Environment.NewLine + " - Instant instant = zonedDateTime.ToInstant();";
        }
        /// <summary>
        /// EXIF DateTime is stored as a string - "yyyy:MM:dd hh:mm:ss" in 24 hour format.
        /// 
        /// Since EXIF datetime does not store timezone info, making the time ambiguous, we grab the user's specified timezone
        /// and assume the image was taken in that timezone.
        /// 
        /// If we don't have a parseable datetime, we set the time to now.
        /// </summary>
        public DateTime ExtractDateTimeFromExif(string dateTimeExif, string timezone)
        {
            var dateTimeStringComponents = dateTimeExif.Split(new[] { ':', ' ' });

            if (dateTimeExif != string.Empty && dateTimeStringComponents.Count() == 6)
            {
                var dateTimeIntComponents = new int[dateTimeStringComponents.Count()];

                for (var i = 0; i < dateTimeStringComponents.Length; i++)
                {
                    int convertedSegment;
                    if (Int32.TryParse(dateTimeStringComponents[i], out convertedSegment))
                    {
                        dateTimeIntComponents[i] = convertedSegment;
                    }
                }

                // Get data into a local time object (no time zone specified)
                var localDateTime = new LocalDateTime(
                        dateTimeIntComponents[0], // year
                        dateTimeIntComponents[1], // month
                        dateTimeIntComponents[2], // day
                        dateTimeIntComponents[3], // hour
                        dateTimeIntComponents[4], // minute
                        dateTimeIntComponents[5], // second
                        CalendarSystem.Iso);

                // Put the local date time into a timezone
                var zonedDateTime = localDateTime.InZoneLeniently(DateTimeZoneProviders.Tzdb[timezone]);

                // Get the UTC date time of the given local date time in the given time zone
                return zonedDateTime.WithZone(DateTimeZone.Utc).ToDateTimeUtc();
            }

            return DateTime.UtcNow;
        }
Beispiel #31
0
 public static DateTime AdjustTzTimeToLocalTime(LocalDateTime theirDateTime, DateTimeZone?theirTimeZone)
 {
     try
     {
         return(theirTimeZone is null
             ? theirDateTime.ToDateTimeUnspecified()
             : theirDateTime.InZoneLeniently(theirTimeZone).ToDateTimeUtc().ToLocalTime());
     }
     catch (ArgumentException)
     {
         try
         {
             Debug.Assert(theirTimeZone != null, nameof(theirTimeZone) + " != null");
             DateTime returnValue = theirDateTime.PlusHours(1).InZoneLeniently(theirTimeZone).ToDateTimeUtc().ToLocalTime();
             Logger.Warn($"Could not convert {theirDateTime} in {theirTimeZone.Id} into {TimeZoneInfo.Local.StandardName} in TimeZoneHelper.AdjustTzTimeToLocalTime (added one hour and it worked ok to account for daylight savings)");
             return(returnValue);
         }
         catch (ArgumentException ae)
         {
             Logger.Error($"Could not convert {theirDateTime} in {theirTimeZone?.Id} into {TimeZoneInfo.Local.StandardName} in TimeZoneHelper.AdjustTzTimeToLocalTime (tried adding one hour too so that we account for daylight saving): {ae.Message}");
             return(theirDateTime.ToDateTimeUnspecified());
         }
     }
 }
 public void InZoneLeniently_AmbiguousTime_ReturnsEarlierMapping()
 {
     var local = new LocalDateTime(2009, 11, 1, 1, 30, 0);
     var zoned = local.InZoneLeniently(Pacific);
     Assert.AreEqual(local, zoned.LocalDateTime);
     Assert.AreEqual(Offset.FromHours(-7), zoned.Offset);
 }
 public void InZoneLeniently_ReturnsStartOfSecondInterval()
 {
     var local = new LocalDateTime(2009, 3, 8, 2, 30, 0);
     var zoned = local.InZoneLeniently(Pacific);
     Assert.AreEqual(new LocalDateTime(2009, 3, 8, 3, 30, 0), zoned.LocalDateTime);
     Assert.AreEqual(Offset.FromHours(-7), zoned.Offset);
 }
        private DateTime WindowsTimeZone(EventDateTime time) {
            DateTime theDate = DateTime.Parse(time.DateTime ?? time.Date);
            if (time.TimeZone == null) return theDate;

            LocalDateTime local = new LocalDateTime(theDate.Year, theDate.Month, theDate.Day, theDate.Hour, theDate.Minute);
            DateTimeZone zone = DateTimeZoneProviders.Tzdb[time.TimeZone];
            ZonedDateTime zonedTime = local.InZoneLeniently(zone);
            DateTime zonedUTC = zonedTime.ToDateTimeUtc();
            log.Fine("IANA Timezone \"" + time.TimeZone + "\" mapped to \""+ zone.Id.ToString() +"\" with a UTC of "+ zonedUTC.ToString("dd/MM/yyyy HH:mm:ss"));
            return zonedUTC;
        }