Esempio n. 1
0
        static void Main(string[] args)
        {
            do
            {
                ReadOnlyCollection <TimeZoneInfo> tzCollection = TimeZoneInfo.GetSystemTimeZones();
                StringBuilder sb = new StringBuilder();
                sb.Append(Environment.NewLine).Append("SET IDENTITY_INSERT [dbo].[TimeZone] ON");
                int i = 1; // SQL default auto increment value

                try
                {
                    foreach (TimeZoneInfo tz in tzCollection)
                    {
                        sb.Append(Environment.NewLine)
                        .Append("INSERT INTO [TimeZone] ([Id], [WindowsId], [DisplayName], [StandardName], [IanaName], [SupportsDaylightSavingTime], [UtcOffsetTicks]) VALUES (N'")
                        .Append(i++).Append("', N'")
                        .Append(tz.Id).Append("', N'")
                        .Append(tz.DisplayName.Replace("'", "''")).Append("', N'")
                        .Append(tz.StandardName).Append("', N'")
                        .Append(TZConvert.WindowsToIana(tz.Id)).Append("', N'")
                        .Append(tz.SupportsDaylightSavingTime).Append("', N'")
                        .Append(tz.BaseUtcOffset.Ticks).Append("');");
                    }
                }
                catch (TimeZoneNotFoundException)
                {
                    Console.WriteLine("COULD NOT CONVERT FROM WIN TO IANA. FOREACH ABORTED.");
                }

                sb.Append(Environment.NewLine).Append("SET IDENTITY_INSERT [dbo].[TimeZone] OFF");
                Console.WriteLine(sb);
            } while (Console.ReadKey(true).Key != ConsoleKey.Escape);
        }
Esempio n. 2
0
        /// <summary>
        /// Get display names suitable for use in a single drop-down list to select a time zone.
        /// </summary>
        /// <param name="languageCode">The IETF language tag (culture code) to use when localizing the display names.</param>
        /// <param name="useIanaZoneIds"><c>true</c> to use IANA time zone keys, otherwise uses Windows time zone keys.</param>
        /// <returns>A dictionary where the key is the time zone id, and the name is the localized display name.</returns>
        public static IDictionary <string, string> GetDisplayNames(string languageCode, bool useIanaZoneIds = false)
        {
            string langKey = GetLanguageKey(languageCode, true);

            if (langKey == null)
            {
                throw new ArgumentException("Invalid Language Code", nameof(languageCode));
            }

            Dictionary <string, string> displayNames = Data.DisplayNames[langKey];

            if (!useIanaZoneIds)
            {
                return(displayNames);
            }

            // Remove obsolete zones before mapping
            displayNames.Remove("Mid-Atlantic Standard Time");
            displayNames.Remove("Kamchatka Standard Time");

            string[] languageCodeParts = languageCode.Split('_', '-');
            string   territoryCode     = languageCodeParts.Length < 2 ? "001" : languageCodeParts[1];

            return(displayNames.ToDictionary(x => TZConvert.WindowsToIana(x.Key, territoryCode), x => x.Value, StringComparer.OrdinalIgnoreCase));
        }
Esempio n. 3
0
        /// <summary>
        /// Called by the framework when the component needs to be rendered as HTML.
        /// </summary>
        /// <param name="model">The model being rendered by the component.</param>
        /// <returns>The component rendered as HTML.</returns>
        public async Task <string> RenderAsync(string model)
        {
            List <TimeZoneInfo> tzis = TimeZoneInfo.GetSystemTimeZones().ToList();
            DateTime            dt   = DateTime.Now;// Need local time

            bool showDefault = PropData.GetAdditionalAttributeValue("ShowDefault", true);

            List <SelectionItem <string> > list;

            if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows))
            {
                list = (
                    from tzi in tzis orderby tzi.DisplayName
                    orderby tzi.DisplayName
                    select
                    new SelectionItem <string> {
                    Text = tzi.DisplayName,
                    Value = tzi.Id,
                    Tooltip = tzi.IsDaylightSavingTime(dt) ? tzi.DaylightName : tzi.StandardName,
                }).ToList <SelectionItem <string> >();
            }
            else
            {
                try {
                    model = TZConvert.WindowsToIana(model);
                } catch (Exception) {
                    model = null;
                }
                tzis = (from tzi in tzis orderby tzi.BaseUtcOffset, tzi.Id select tzi).ToList();

                list = new List <SelectionItem <string> >();
                foreach (TimeZoneInfo tzi in tzis)
                {
                    TimeSpan ts   = tzi.BaseUtcOffset;
                    int      h    = ts.Hours;
                    string   disp = $"(UTC{(h > 0 ? "+" : "-")}{Math.Abs(h):00}:{ts.Minutes:00}) {tzi.Id}";
                    list.Add(new SelectionItem <string> {
                        Text    = disp,
                        Value   = tzi.Id,
                        Tooltip = tzi.IsDaylightSavingTime(dt) ? tzi.DaylightName : tzi.StandardName,
                    });
                }
            }

            if (showDefault)
            {
                if (string.IsNullOrWhiteSpace(model))
                {
                    model = TimeZoneInfo.Local.Id;
                }
            }
            else
            {
                list.Insert(0, new SelectionItem <string> {
                    Text = __ResStr("select", "(select)"), Value = ""
                });
            }

            return(await DropDownListComponent.RenderDropDownListAsync(this, model, list, "yt_timezone"));
        }
Esempio n. 4
0
        static void Main(string[] args)
        {
            Load();

            foreach (var iana in TZConvert.KnownIanaTimeZoneNames)
            {
                if (!Zones.Exists(z => z.Iana == iana && z.Windows == TZConvert.IanaToWindows(iana)))
                {
                    Zones.Add(new Zone {
                        Iana = iana, Windows = TZConvert.IanaToWindows(iana)
                    });
                }
            }

            foreach (var windows in TZConvert.KnownWindowsTimeZoneIds)
            {
                if (!Zones.Exists(z => z.Iana == TZConvert.WindowsToIana(windows) && z.Windows == windows))
                {
                    Zones.Add(new Zone {
                        Iana = TZConvert.WindowsToIana(windows), Windows = windows
                    });
                }
            }

            Zones = Zones
                    .DistinctBy(z => (z.Iana, z.Windows))
                    .ToList();

            Save();

            Console.WriteLine("All z[tz]: " + Zones.All(z => TimeZoneInfo.GetSystemTimeZones().Any(tz => tz.Id == z.Windows || tz.Id == z.Iana)));
            Console.WriteLine("All tz[z]: " + TimeZoneInfo.GetSystemTimeZones().All(tz => Zones.Any(z => tz.Id == z.Windows || tz.Id == z.Iana)));
        }
Esempio n. 5
0
        public DateTime GetDateUtcNow(DateTime date)
        {
            //SE for teste de desenvolvimento, ira pegar a hora da maquina local;
            var TesteDesenvolvimento = false;

            if (TesteDesenvolvimento)
            {
                return(date);
            }

            string tz = "";

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                tz = TZConvert.IanaToWindows("America/Sao_Paulo");
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                tz = TZConvert.WindowsToIana("E. South America Standard Time");
            }

            var cetZone = TimeZoneInfo.FindSystemTimeZoneById(tz);

            return(TimeZoneInfo.ConvertTime(date, cetZone));
        }
Esempio n. 6
0
        private void CalculateDuration()
        {
            DateTime start = new DateTime(_viewModel.StartYear, _viewModel.StartMonth, _viewModel.StartDay, _viewModel.StartHours, _viewModel.StartMinutes, 0);
            DateTime end   = new DateTime(_viewModel.EndYear, _viewModel.EndMonth, _viewModel.EndDay, _viewModel.EndHours, _viewModel.EndMinutes, 0);

            _viewModel.CurrentSleep.SleepStart = start;
            _viewModel.CurrentSleep.SleepEnd   = end;
            if (_userInfo != null)
            {
                try
                {
                    TimeZoneInfo.FindSystemTimeZoneById(_userInfo.Timezone);
                }
                catch (Exception)
                {
                    _userInfo.Timezone = TZConvert.WindowsToIana(_userInfo.Timezone);
                }

                DateTimeOffset sOffset = new DateTimeOffset(_viewModel.CurrentSleep.SleepStart,
                                                            TimeZoneInfo.FindSystemTimeZoneById(_userInfo.Timezone).GetUtcOffset(_viewModel.CurrentSleep.SleepStart));
                DateTimeOffset eOffset = new DateTimeOffset(_viewModel.CurrentSleep.SleepEnd,
                                                            TimeZoneInfo.FindSystemTimeZoneById(_userInfo.Timezone).GetUtcOffset(_viewModel.CurrentSleep.SleepEnd));
                _viewModel.CurrentSleep.SleepDuration = eOffset - sOffset;
                _viewModel.Duration = eOffset - sOffset;
            }
        }
Esempio n. 7
0
        private void OnInitialize(ICommunicationMessage e, string clientVersion)
        {
            if (clientVersion != typeof(Program).Assembly.GetName().Version.ToString())
            {
                this.Logger.Warn($"Client version does not match server version, got {clientVersion}, expecting {typeof(Program).Assembly.GetName().Version}, dropping client: {e.Client.Handle}");

                API.DropPlayer(e.Client.Handle.ToString(), "Please reconnect to get the latest NFive client version");

                return;
            }

            this.comms.Event(SessionEvents.ClientInitializing).ToServer().Emit(e.Client);

            var logs = new Tuple <LogLevel, LogLevel>(
                ServerLogConfiguration.Output.ClientConsole,
                ServerLogConfiguration.Output.ClientMirror
                );

            var locale = new Tuple <List <string>, string>(
                ServerConfiguration.Locale.Culture.Select(c => c.Name).ToList(),
                TZConvert.WindowsToIana(ServerConfiguration.Locale.TimeZone.Id, new RegionInfo(ServerConfiguration.Locale.Culture.First().Name).TwoLetterISORegionName)
                );

            e.Reply(e.User, logs, locale);
        }
Esempio n. 8
0
        public async Task <object> GetMasjidById(string id)
        {
            var d = await _taqweemService
                    .MasjidGetByIdAsync(id);

            MasjidDTO returnObject = new MasjidDTO
            {
                Id                  = d.Id,
                Name                = d.Name,
                Town                = d.Town,
                Country             = d.Country,
                LastUpdate          = d.LastUpdate,
                Latitude            = d.Latitude,
                Longitude           = d.Longitude,
                Height              = d.Height,
                TimeZoneId          = d.TimeZoneId,
                JuristMethod        = d.JuristMethod,
                LadiesFacility      = d.LadiesFacility,
                JummahFacility      = d.JummahFacility,
                Contact             = d.Contact,
                Address             = d.Address,
                GeneralInfo         = d.GeneralInfo,
                MaghribAdhaanDelay  = d.MaghribAdhaanDelay,
                SalaahTimesType     = d.SalaahTimesType,
                IsSpecialDayEnabled = d.IsSpecialDayEnabled,
                IsPublicHolidaySpecialTimesEnabled = d.IsPublicHolidaySpecialTimesEnabled,
                SpecialDayNumber = d.SpecialDayNumber,
                TZTimeZone       = TZConvert.WindowsToIana(d.TimeZoneId)
            };

            return(returnObject);
        }
        public Calendar ExportCalendar(DomainCalendar calendar)
        {
            var iCalendar = new Calendar();

            iCalendar.TimeZones.Add(new VTimeZone(TimeZoneInfo.Utc.Id));

            iCalendar.Properties.Add(new CalendarProperty("X-WR-CALNAME", calendar.Name));
            iCalendar.Properties.Add(new CalendarProperty("X-WR-TIMEZONE", TZConvert.WindowsToIana(TimeZoneInfo.Utc.Id)));

            foreach (var e in calendar.Events)
            {
                var iEvent = new CalendarEvent
                {
                    Summary     = e.Event.Name,
                    Description = e.Event.Description,
                    IsAllDay    = e.Event.IsAllDay
                };

                if (e.Event.Location != null)
                {
                    iEvent.GeographicLocation = new GeographicLocation(e.Event.Location.Lattitude.Value, e.Event.Location.Longitude.Value);
                    iEvent.Location           = e.Event.Location.Description;
                }

                if (e.Event.Period == null)
                {
                    if (e.Event.IsAllDay)
                    {
                        iEvent.DtStart = new CalDateTime(e.Event.StartDate.Value);
                        iEvent.DtEnd   = new CalDateTime(e.Event.EndDate.Value.AddDays(1).AddMinutes(-1));
                    }
                    else
                    {
                        iEvent.DtStart = new CalDateTime(e.Event.StartDate.Value.Add(e.Event.StartTime.Value));
                        iEvent.DtEnd   = new CalDateTime(e.Event.EndDate.Value.Add(e.Event.EndTime.Value));
                    }
                }
                else
                {
                    if (e.Event.IsAllDay)
                    {
                        iEvent.DtStart = new CalDateTime(e.Event.Period.PeriodStart);
                        iEvent.DtEnd   = new CalDateTime(e.Event.Period.PeriodStart.AddDays(1).AddMinutes(-1));
                    }
                    else
                    {
                        iEvent.DtStart = new CalDateTime(e.Event.Period.PeriodStart.Add(e.Event.StartTime.Value));
                        iEvent.DtEnd   = new CalDateTime(e.Event.Period.PeriodEnd.Add(e.Event.EndTime.Value));
                    }

                    iEvent.RecurrenceRules = new List <RecurrencePattern> {
                        _GetRecurrencePattern(e.Event)
                    };
                }

                iCalendar.Events.Add(iEvent);
            }

            return(iCalendar);
        }
Esempio n. 10
0
 static partial void GetTimeZoneIdImpl(TimeZoneInfo timeZoneInfo, ref string?timeZoneCode)
 {
     timeZoneCode = timeZoneInfo.Id;
     if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
     {
         timeZoneCode = TZConvert.WindowsToIana(timeZoneCode);
     }
 }
Esempio n. 11
0
        public static DateTime GetLocalDateTime(DateTime dateTime, string timeZone)
        {
            var ianaTz = TZConvert.WindowsToIana(timeZone);

            var localTime     = LocalDateTime.FromDateTime(dateTime);
            var zonedDateTime = localTime.InZoneStrictly(DateTimeZoneProviders.Tzdb[ianaTz]);

            return(zonedDateTime.LocalDateTime.ToDateTimeUnspecified());
        }
Esempio n. 12
0
        public static string ToIana(this TimeZoneInfo tz)
        {
            if (OperatingSystem.IsMacOS())
            {
                return(tz.Id);
            }

            return(TZConvert.WindowsToIana(tz.Id));
        }
Esempio n. 13
0
        // This will return the "primary" IANA zone that matches the given windows zone.
        public static string WindowsToIana(string windowsZoneId)
        {
            //var tzdbSource = NodaTime.TimeZones.TzdbDateTimeZoneSource.Default;
            //var tzi = TimeZoneInfo.FindSystemTimeZoneById(windowsZoneId);
            //var aliases = tzdbSource.WindowsMapping.PrimaryMapping[tzi.Id]; //.MapTimeZoneId(tzi);

            //return aliases;
            var ianaTz = TZConvert.WindowsToIana(windowsZoneId);

            return(ianaTz);
        }
        //lists Windows Zones with matching IANA Zones
        public IHttpActionResult GetTimeZones()
        {
            var tzs = TimeZoneInfo.GetSystemTimeZones();

            return(Ok(tzs.Select(t => new TimeZone
            {
                WindowsZoneId = t.Id,
                IanaZoneId = TZConvert.WindowsToIana(t.Id),
                DisplayName = t.DisplayName
            })));
        }
Esempio n. 15
0
        /// <summary>
        /// Ideally we would use library that has the same breadth as the factset data source does for different timezones
        /// We know that their format is windows-like but has additional entries
        /// This is a plaster - replace it with a good timezone library
        /// </summary>
        private static string ConvertWindowsToIana(string timezone, string countryCode)
        {
            if (string.Equals(timezone, "AUS Eastern Daylight Time", StringComparison.OrdinalIgnoreCase))
            {
                timezone = "AUS Eastern Standard Time";
            }

            var ianaTimeZone = TZConvert.WindowsToIana(timezone, countryCode);

            return(ianaTimeZone);
        }
Esempio n. 16
0
        public static string ToTzdb(TimeZoneInfo timeZoneInfo)
        {
            if (timeZoneInfo.Id.Contains("/"))
            {
                return(timeZoneInfo.Id);
            }

            var item = TZConvert.WindowsToIana(timeZoneInfo.Id);

            return(item);
        }
Esempio n. 17
0
        public static TimeZoneInfo GetTimeZoneInfo(string zoneName)
        {
            TimeZoneInfo timeZoneInfo;

            try
            {
                timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(zoneName);
            }
            catch (Exception)
            {
                timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(TZConvert.WindowsToIana(zoneName));
            }
            return(timeZoneInfo);
        }
Esempio n. 18
0
        public void Can_Convert_Windows_Zones_To_Iana_Regional_Zones()
        {
            var result1 = TZConvert.WindowsToIana("Central Europe Standard Time", "CZ");

            Assert.Equal("Europe/Prague", result1);

            var result2 = TZConvert.WindowsToIana("Central Europe Standard Time", "foo");

            Assert.Equal("Europe/Budapest", result2);

            var result3 = TZConvert.WindowsToIana("Central Europe Standard Time");

            Assert.Equal("Europe/Budapest", result3);
        }
Esempio n. 19
0
        public void Can_Convert_Non_Canonical()
        {
            string result1 = TZConvert.WindowsToIana("US Eastern Standard Time", resolveCanonical: false);

            Assert.Equal("America/Indianapolis", result1);

            string result2 = TZConvert.WindowsToIana("India Standard Time", resolveCanonical: false);

            Assert.Equal("Asia/Calcutta", result2);

            string result3 = TZConvert.WindowsToIana("Nepal Standard Time", resolveCanonical: false);

            Assert.Equal("Asia/Katmandu", result3);
        }
Esempio n. 20
0
        public void Can_Convert_Canonical()
        {
            string result1 = TZConvert.WindowsToIana("US Eastern Standard Time");

            Assert.Equal("America/Indiana/Indianapolis", result1);

            string result2 = TZConvert.WindowsToIana("India Standard Time");

            Assert.Equal("Asia/Kolkata", result2);

            string result3 = TZConvert.WindowsToIana("Nepal Standard Time");

            Assert.Equal("Asia/Kathmandu", result3);
        }
Esempio n. 21
0
        public static Event ToGoogleEvent(this IAppointment appointment, int?sequence = null, string uniqueId = null)
        {
            if (appointment.Schedule == null)
            {
                throw new ArgumentException("Appointment does not contain schedule");
            }

            var ev = new Event
            {
                Transparency = appointment.Busy ? "opaque" : "transparent",
                Summary      = appointment.Subject,
                Location     = appointment.Location,
                ICalUID      = uniqueId,
                Sequence     = sequence,
                Status       = appointment.Confirmed ? "confirmed" : "tentative",
                Reminders    = new Event.RemindersData
                {
                    UseDefault = false,
                },
                Recurrence = appointment.Schedule.ToRfc5545Rules().ToList(),
            };

            if (appointment.Schedule.AllDay)
            {
                ev.Start = new EventDateTime
                {
                    Date = appointment.Schedule.Start.Date.ToString("yyyy-MM-dd"),
                };
                ev.End = new EventDateTime
                {
                    Date = appointment.Schedule.End.Date.ToString("yyyy-MM-dd"),
                };
            }
            else
            {
                ev.Start = new EventDateTime
                {
                    DateTime = appointment.Schedule.Start,
                    TimeZone = TZConvert.WindowsToIana(appointment.Schedule.StartTimeZone.Id),
                };
                ev.End = new EventDateTime
                {
                    DateTime = appointment.Schedule.End,
                    TimeZone = TZConvert.WindowsToIana(appointment.Schedule.EndTimeZone.Id),
                };
            }

            return(ev);
        }
Esempio n. 22
0
        public static async Task <UserInfo> UpdateUserInfo(UserInfo updatedUserInfo)
        {
            if (ProgenyService.Online())
            {
                var client = new HttpClient();
                client.BaseAddress = new Uri(Constants.ProgenyApiUrl);
                string accessToken = await UserService.GetAuthAccessToken();

                client.SetBearerToken(accessToken);
                try
                {
                    var result = await client.PutAsync("api/userinfo/" + updatedUserInfo.UserId, new StringContent(JsonConvert.SerializeObject(updatedUserInfo), Encoding.UTF8, "application/json")).ConfigureAwait(false);

                    if (result.IsSuccessStatusCode)
                    {
                        string resultString = await result.Content.ReadAsStringAsync();

                        UserInfo resultUserInfo = JsonConvert.DeserializeObject <UserInfo>(resultString);

                        await SecureStorage.SetAsync(Constants.UserNameKey, resultUserInfo.UserName);

                        await SecureStorage.SetAsync(Constants.UserFirstNameKey, resultUserInfo.FirstName);

                        await SecureStorage.SetAsync(Constants.UserMiddleNameKey, resultUserInfo.MiddleName);

                        await SecureStorage.SetAsync(Constants.UserLastNameKey, resultUserInfo.LastName);

                        try
                        {
                            TimeZoneInfo.FindSystemTimeZoneById(resultUserInfo.Timezone);
                        }
                        catch (Exception)
                        {
                            resultUserInfo.Timezone = TZConvert.WindowsToIana(resultUserInfo.Timezone);
                        }
                        await SecureStorage.SetAsync(Constants.UserTimezoneKey, resultUserInfo.Timezone);

                        return(resultUserInfo);
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    return(new UserInfo());
                }
            }

            return(new UserInfo());
        }
Esempio n. 23
0
        public static TimeZoneInfo TimeZoneInfoGetter(string fromGmt)
        {
            var gmt = ReformatGMT(fromGmt);
            var windowsTimeZoneId = TimeZones[gmt];

            try
            {
                return(TimeZoneInfo.FindSystemTimeZoneById(windowsTimeZoneId));
            }
            catch (Exception)
            {
                var linuxTimeZoneId = TZConvert.WindowsToIana(windowsTimeZoneId);
                return(TimeZoneInfo.FindSystemTimeZoneById(linuxTimeZoneId));
            }
        }
Esempio n. 24
0
 /// <summary>
 /// 获取windows时区转换为其他时区依据操作系统平台
 /// </summary>
 /// <param name="windowsTimeZoneId"></param>
 /// <returns></returns>
 private static string GetWindowsZoneIdToOtherZoneByPlatform(string windowsTimeZoneId = "China Standard Time")
 {
     if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
     {
         return(TZConvert.WindowsToIana(windowsTimeZoneId?.TrimEnd()));
     }
     else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
     {
         return(windowsTimeZoneId);
     }
     else
     {
         return("无法识别操作系统");
     }
 }
Esempio n. 25
0
        private DateTimeZone FigureOutTimeZone()
        {
            string tzstr = ShowTimeZone;

            if (string.IsNullOrEmpty(tzstr))
            {
                tzstr = TimeZoneHelper.DefaultTimeZone();
            }

            try
            {
                return(DateTimeZoneProviders.Tzdb[tzstr]);
            }
            catch (Exception ex)
            {
                LOGGER.Info($"Could not work out what timezone '{ShowName}' has. In the settings it uses '{tzstr}', Testing to see whether it needs to be upgraded: {ex.Message}");
                try
                {
                    tzstr         = TZConvert.WindowsToIana(tzstr);
                    ShowTimeZone  = tzstr;
                    lastFiguredTz = tzstr;
                    return(DateTimeZoneProviders.Tzdb[tzstr]);
                }
                catch (Exception ex2)
                {
                    LOGGER.Warn(ex2,
                                $"Could not work out what timezone '{ShowName}' has. In the settings it uses '{tzstr}', but that is not valid. Please update. Using the default timezone {TimeZoneHelper.DefaultTimeZone()} for the show instead.");

                    try
                    {
                        tzstr         = TimeZoneHelper.DefaultTimeZone();
                        ShowTimeZone  = tzstr;
                        lastFiguredTz = tzstr;
                        return(DateTimeZoneProviders.Tzdb[tzstr]);
                    }
                    catch (Exception ex3)
                    {
                        LOGGER.Warn(ex3,
                                    $"Could not work out what timezone '{ShowName}' has. In the settings it uses '{tzstr}', but that is not valid. Tried to use the default timezone {TimeZoneHelper.DefaultTimeZone()} for the show instead - also invalid.  Please update.");


                        ShowTimeZone  = DateTimeZoneProviders.Tzdb.GetSystemDefault().Id;
                        lastFiguredTz = tzstr;
                        return(DateTimeZoneProviders.Tzdb.GetSystemDefault());
                    }
                }
            }
        }
Esempio n. 26
0
 public CurrentTimeQuery() //Constructor to fill SelectListItem TimezoneList before it is passed to view
 {
     try
     {
         var tzs = TimeZoneInfo.GetSystemTimeZones();
         TimezoneList = tzs.Select(tz => new SelectListItem()
         {
             Text  = tz.DisplayName.Substring(12),
             Value = TZConvert.WindowsToIana(tz.Id)
         }).ToArray();
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
        public void Can_Convert_UTC_Aliases()
        {
            var result1 = TZConvert.WindowsToIana("UTC");

            Assert.Equal("Etc/UTC", result1);

            var utcAliases = "Etc/UTC Etc/UCT Etc/Universal Etc/Zulu UCT UTC Universal Zulu".Split();
            var gmtAliases = "Etc/GMT Etc/GMT+0 Etc/GMT-0 Etc/GMT0 Etc/Greenwich GMT GMT+0 GMT-0 GMT0 Greenwich".Split();
            var aliases    = utcAliases.Concat(gmtAliases);

            foreach (var alias in aliases)
            {
                var result2 = TZConvert.IanaToWindows(alias);
                Assert.Equal(alias + ":UTC", alias + ":" + result2);
            }
        }
Esempio n. 28
0
        public static DateTime ConvertToUtc(DateTime dateTime, string timeZone)
        {
            //var tzdbSource = NodaTime.TimeZones.TzdbDateTimeZoneSource.Default;
            //var tzi = TimeZoneInfo.FindSystemTimeZoneById(IanaToWindows(timeZone));

            //Instant instant = Instant.FromDateTimeUtc(dateTime);
            //ZonedDateTime zonedDateTime = new ZonedDateTime(instant, DateTimeZoneProviders.Tzdb[timeZone]);

            //LocalDateTime localDateTime = new LocalDateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second);
            //ZonedDateTime zonedDateTime = new ZonedDateTime(localDateTime, DateTimeZoneProviders.Tzdb[timeZone]);

            var ianaTz = TZConvert.WindowsToIana(timeZone);

            var localTime     = LocalDateTime.FromDateTime(dateTime);
            var zonedDateTime = localTime.InZoneStrictly(DateTimeZoneProviders.Tzdb[ianaTz]);

            return(zonedDateTime.ToDateTimeUtc());
        }
Esempio n. 29
0
        static DateTimeZones()
        {
            const string WindowsMoscowTime = "Russian Standard Time";

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                MoscowInfo = TimeZoneInfo.FindSystemTimeZoneById(WindowsMoscowTime);
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                string linux = TZConvert.WindowsToIana(WindowsMoscowTime);

                MoscowInfo = TimeZoneInfo.FindSystemTimeZoneById(linux);
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                throw new NotImplementedException("Cannot get moscow time for OSX OS");
            }
        }
Esempio n. 30
0
        public async Task Run([ActivityTrigger] TeamModel teamModel, ILogger log)
        {
            var schedule = await _scheduleDestinationService.GetScheduleAsync(teamModel.TeamId);

            if (schedule.IsUnavailable)
            {
                string timeZoneInfoId;
                if (string.IsNullOrEmpty(teamModel.TimeZoneInfoId))
                {
                    timeZoneInfoId = _options.TimeZone;
                }
                else
                {
                    timeZoneInfoId = TZConvert.WindowsToIana(teamModel.TimeZoneInfoId);
                }

                var scheduleModel = ScheduleModel.Create(timeZoneInfoId);

                await _scheduleDestinationService.CreateScheduleAsync(teamModel.TeamId, scheduleModel);
            }
            else if (schedule.IsProvisioned)
            {
                log.LogSchedule(teamModel, schedule);

                return;
            }

            for (var i = 0; i < _options.PollMaxAttempts; i++)
            {
                await Task.Delay(_options.AsPollIntervalTimeSpan());

                schedule = await _scheduleDestinationService.GetScheduleAsync(teamModel.TeamId);

                log.LogSchedule(teamModel, schedule);

                if (schedule.IsProvisioned)
                {
                    return;
                }
            }

            throw new TimeoutException();
        }