Beispiel #1
0
        public static IpApiResult GetInfo(string ip)
        {
            try
            {
                var result = new IpApiResult();

                using (var reader = new DatabaseReader($"{AppDomain.CurrentDomain.BaseDirectory}GeoDb\\GeoLite2-City.mmdb"))
                {
                    var city = reader.City(ip);
                    if (city == null)
                    {
                        return(null);
                    }
                    result.Country  = city.Country.IsoCode;
                    result.Timezone = city.Location.TimeZone;

                    result.WZoneid = TZConvert.IanaToWindows(result.Timezone);
                    result.Offset  = GetOffset(result.Timezone);
                }

                return(result);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
        private static void GenerateIANAtoTZIdMap(string baseDir)
        {
            var map       = new StringBuilder();
            var ianaNames = TZConvert.KnownIanaTimeZoneNames;

            foreach (var ianaName in ianaNames)
            {
                var tzid = TZConvert.IanaToWindows(ianaName);
                map.Append("\\u0002" + ianaName + "\t" + tzid + "\\u0003");
            }

            var buff = new List <string>();

            buff.Add("namespace Toolbelt.Blazor.TimeZoneKit");
            buff.Add("{");
            buff.Add("    public static partial class TimeZoneKit");
            buff.Add("    {");
            buff.Add("        private const string IANAtoTZIdMap = \"" + map.ToString() + "\";");
            buff.Add("    }");
            buff.Add("}");

            var path = Path.Combine(baseDir, "TimeZoneKit.IANAtoTZIdMap.cs");

            File.WriteAllLines(path, buff);
        }
Beispiel #3
0
 public void SetTimeZones(string timezones)
 {
     clocks.Clear();
     string[] tzs = timezones.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
     foreach (string tz in tzs)
     {
         Clock clock = new Clock();
         try
         {
             string name = TZConvert.IanaToWindows(tz);
             clock.iana     = tz;
             clock.timezone = TimeZoneInfo.FindSystemTimeZoneById(name);
             clock.name     = TZNames.GetNamesForTimeZone(tz, "en").Generic.Replace(" Time", "").Replace("Coordinated ", "");
             clock.abbr     = TZNames.GetAbbreviationsForTimeZone(tz, "en").Generic;
             clock.city     = ToCity(tz);
             clock.diff     = ToDiff(clock.timezone);
             clock.color    = clock.timezone.GetUtcOffset(DateTime.Now) == TimeZoneInfo.Local.GetUtcOffset(DateTime.Now) ? current : transparent;
             UpdateClock(clock);
             clocks.Add(clock);
         }
         catch (Exception e)
         {
         }
     }
     if (widget != null)
     {
         Windows.Foundation.Size size;
         size.Height = 160;
         size.Width  = 160 * clocks.Count;
         widget.TryResizeWindowAsync(size);
     }
 }
        public async Task <IActionResult> SaveTimeZoneAsync([FromBody] UserConfigurationEntity configuration)
        {
            if (configuration == null)
            {
                return(this.BadRequest(new { message = "Configuration details parameter is null." }));
            }

            try
            {
                var claims = this.GetUserClaims();
                this.telemetryClient.TrackTrace($"User {claims.UserObjectIdentifer} submitted settings. Time zone- {configuration.IanaTimezone}");
                configuration.UserAdObjectId  = claims.UserObjectIdentifer;
                configuration.WindowsTimezone = TZConvert.IanaToWindows(configuration.IanaTimezone);

                var isAddOperationSuccess = await this.userConfigurationStorageProvider.AddAsync(configuration).ConfigureAwait(false);

                if (isAddOperationSuccess)
                {
                    return(this.Ok("Configuration saved"));
                }

                return(this.StatusCode(StatusCodes.Status500InternalServerError, "Unable to save user configuration/time zone"));
            }
            catch (Exception ex)
            {
                this.telemetryClient.TrackException(ex);
                return(this.StatusCode(StatusCodes.Status500InternalServerError, ex.Message));
            }
        }
Beispiel #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));
        }
Beispiel #6
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)));
        }
Beispiel #7
0
        private Status GetStatus(DateTime activationDateAndTime, TimeSpan durationOfActivity, string quizId, string timeZone)
        {
            var zone             = TimeZoneInfo.FindSystemTimeZoneById(TZConvert.IanaToWindows(timeZone));
            var userLocalTimeNow = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, zone);
            var activationDateAndTimeToUserLocalTime = TimeZoneInfo.ConvertTimeFromUtc(activationDateAndTime, zone);

            if (quizId == null ||
                userLocalTimeNow.Date < activationDateAndTimeToUserLocalTime.Date ||
                activationDateAndTimeToUserLocalTime.TimeOfDay > userLocalTimeNow.TimeOfDay)
            {
                return(Status.Pending);
            }

            var startHours = activationDateAndTimeToUserLocalTime.TimeOfDay.Hours;
            var nowHours   = userLocalTimeNow.TimeOfDay.Hours;
            var startMins  = activationDateAndTimeToUserLocalTime.TimeOfDay.Minutes;
            var nowMins    = userLocalTimeNow.TimeOfDay.Minutes;

            var endHours   = activationDateAndTimeToUserLocalTime.Add(durationOfActivity).TimeOfDay.Hours;
            var endMinutes = activationDateAndTimeToUserLocalTime.Add(durationOfActivity).TimeOfDay.Minutes;

            if (startHours <= nowHours && startMins <= nowMins &&
                (endHours > nowHours || (endHours == nowHours && endMinutes >= nowMins)))
            {
                return(Status.Active);
            }

            return(Status.Ended);
        }
Beispiel #8
0
        public async Task <TimeZoneInfo> GetTimeZone(float lat, float lon)
        {
            var queryParams = HttpUtility.ParseQueryString(string.Empty);

            queryParams["api-version"]      = "1.0";
            queryParams["subscription-key"] = AppSettings.AzureMapServiceKey;
            queryParams["query"]            = $"{lat},{lon}";

            var requestUrlBuilder = new UriBuilder(AppSettings.AzureMapsTimeZoneUrl)
            {
                Query = queryParams.ToString(),
            };

            var requestUrl = requestUrlBuilder.ToString();

            var response = await Client.GetAsync(requestUrl);

            var azureTimeZoneResponse = JsonConvert.DeserializeObject <AzureTimeZoneResponse>(await response.Content.ReadAsStringAsync());

            var timeZoneId = azureTimeZoneResponse.TimeZones[0].Id;

            // The timezones from Azure Maps come back in Unix timezone Id format
            // If running on Windows we need to convert
            try
            {
                return(TimeZoneInfo.FindSystemTimeZoneById(timeZoneId));
            }
            catch
            {
                return(TimeZoneInfo.FindSystemTimeZoneById(TZConvert.IanaToWindows(timeZoneId)));
            }
        }
Beispiel #9
0
 public IActionResult CheckTimezone(string timezone)
 {
     if (string.IsNullOrWhiteSpace(UserTimezone))
     {
         UserTimezone = TZConvert.IanaToWindows(timezone);
     }
     return(Ok(UserTimezone));
 }
Beispiel #10
0
        public static String GetTimeZoneInfo(this String s)
        {
            if (string.IsNullOrEmpty(s))
            {
                s = Constant.UsDefaultTime;
            }
            string tz = TZConvert.IanaToWindows(s);

            return(tz.ToFirstLetter());
        }
        private TimeZoneInfo TimeZoneInfoFactory(string ianaTimeZoneName)
        {
            if (string.IsNullOrWhiteSpace(ianaTimeZoneName))
            {
                return(TimeZoneInfo.Local);
            }
            var microsoftTimeZoneId = TZConvert.IanaToWindows(ianaTimeZoneName);

            return(TimeZoneInfo.FindSystemTimeZoneById(microsoftTimeZoneId));
        }
        public static DateTime ToLosAngerlesTimeWithTimeZone(this DateTime currentDate, string destinationTimeZoneId)
        {
            if (string.IsNullOrEmpty(destinationTimeZoneId))
            {
                return(currentDate.ToLosAngerlesTime());
            }

            string tz = TZConvert.IanaToWindows(destinationTimeZoneId);

            return(TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentDate, TimeZoneInfo.Utc.Id, tz));
        }
 public static string ConvertIanaIdToWindowsTime(string IanaId)
 {
     try
     {
         return(TZConvert.IanaToWindows(IanaId));
     }
     catch (Exception)
     {
         return("Eastern Standard Time");
     }
 }
        public void TestMethod1()
        {
            foreach (var tz in TimeZoneInfo.GetSystemTimeZones())
            {
                var name = Environment.OSVersion.Platform.ToString().StartsWith("Win")
          ? tz.Id
          : TZConvert.IanaToWindows(tz.Id);
            }

            Assert.IsNotNull(TimeZones.EasternStandardTime);
        }
        private TimeZoneInfo GetTimeZone(string tzName)
        {
            var timeZone = RuntimeInformation.IsOSPlatform(OSPlatform.Linux)
                               ? TimeZoneInfo.FindSystemTimeZoneById(tzName)
                               : TimeZoneInfo.FindSystemTimeZoneById(TZConvert.IanaToWindows(tzName));

            if (timeZone == null)
            {
                throw new ApplicationException("No timeZone found");
            }

            return(timeZone);
        }
        public static DateTime ConvertTimeFromCoordinates(this DateTime date, double lat, double lon)
        {
            var tzIana = TimeZoneLookup.GetTimeZone(lat, lon).Result;

#if Windows
            // Convert to Windows acceptable TimeZone
            tzIana = TZConvert.IanaToWindows(tzIana);
#endif
            var tzInfo        = TimeZoneInfo.FindSystemTimeZoneById(tzIana);
            var dt            = DateTime.SpecifyKind(date, DateTimeKind.Utc);
            var convertedTime = TimeZoneInfo.ConvertTimeFromUtc(dt, tzInfo);
            return(convertedTime);
        }
Beispiel #17
0
 public static TimeZoneInfo ToTimeZoneInfo(string windowsOrIanaTimeZoneId)
 {
     try {
         // Try a direct approach first
         return(TimeZoneInfo.FindSystemTimeZoneById(windowsOrIanaTimeZoneId));
     } catch {
         // We have to convert to the opposite platform
         //bool isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
         //if (!isWindows) { timeZoneId = TZConvert.WindowsToIana(windowsOrIanaTimeZoneId); }
         var timeZoneId = TZConvert.IanaToWindows(windowsOrIanaTimeZoneId);
         return(TimeZoneInfo.FindSystemTimeZoneById(timeZoneId));
     }
 }
        /// <summary>
        /// A helper to get corresponding windows timezone for input Iana timezone
        /// </summary>
        /// <param name="timezoneAbbreviation"></param>
        /// <returns>The windows timezone name string. Returns empty string if invalid</returns>
        public static string GetWindowsTimeZoneName(string timezoneAbbreviation)
        {
            string standardWindowsTime;

            try
            {
                standardWindowsTime = TZConvert.IanaToWindows(timezoneAbbreviation);
            }
            catch
            {
                standardWindowsTime = string.Empty;
            }
            return(standardWindowsTime);
        }
 static TimeZoneInfo TryParse(string timezoneId, bool convertFromIana = false)
 {
     try
     {
         return(TimeZoneInfo.FindSystemTimeZoneById(
                    convertFromIana
                 ? TZConvert.IanaToWindows(timezoneId)
                 : timezoneId));
     }
     catch
     {
         return(null);
     }
 }
Beispiel #20
0
        public static string GetOpenStatus(Place place)
        {
            var tzIana = TimeZoneLookup.GetTimeZone(place.Latitude, place.Longitude).Result;
            var tzMs   = TZConvert.IanaToWindows(tzIana);
            var tzInfo = TimeZoneInfo.FindSystemTimeZoneById(tzMs);
            var now    = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tzInfo);

            var isWeekend = now.DayOfWeek == DayOfWeek.Saturday || now.DayOfWeek == DayOfWeek.Sunday;

            return(!isWeekend & now.TimeOfDay > place.OpenTime && now.TimeOfDay < place.CloseTime ||
                   isWeekend & now.TimeOfDay > place.OpenTimeWeekend && now.TimeOfDay < place.CloseTimeWeekend
                    ? String.Empty
                    : "🔒 ");
        }
Beispiel #21
0
        public ScheduleController(IScheduleService service, IHttpContextAccessor accessor)
        {
            _service  = service;
            _accessor = accessor;

            var zoneId = _accessor.HttpContext.Request.Cookies["tzTime"] ?? "Asia/Taipei";

            _customerTimezone = TimeZoneInfo.FindSystemTimeZoneById(TZConvert.IanaToWindows(zoneId));
            _systemTimezone   = TimeZoneInfo.Local;

            var cultureId = _accessor.HttpContext.Request.Cookies["culture"] ?? "zh-TW";

            _culture = CultureInfo.CreateSpecificCulture(cultureId);
        }
        //Pass in moment.guess() IANA Zone to determine Windows Zone
        public IHttpActionResult GetMyTimeZone([FromUri] string ianaZoneId)
        {
            string windowsZoneId;

            try
            {
                windowsZoneId = TZConvert.IanaToWindows(ianaZoneId);
            }
            catch (InvalidTimeZoneException)
            {
                windowsZoneId = "Timezone not found";
            }

            return(Ok(windowsZoneId));
        }
        public void TimezonesMissingIanaTests()
        {
            ICollection <string> tzCollection = TZConvert.KnownIanaTimeZoneNames;

            foreach (string timezone in tzCollection)
            {
                try
                {
                    TZConvert.IanaToWindows(timezone);
                }
                catch (InvalidTimeZoneException)
                {
                    Output.WriteLine(timezone + "=>" + "MISSING !!!");
                }
            }
        }
Beispiel #24
0
 /// <summary>
 /// Called before action runs.
 /// </summary>
 /// <remarks>Used to normalize timezones.</remarks>
 public static Task <string> ControllerPreprocessActionAsync(string propName, string model, ModelStateDictionary modelState)
 {
     if (!System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows))
     {
         // On linux we need to translate the timezone id to a "windows" timezone id
         if (!string.IsNullOrWhiteSpace(model))
         {
             try {
                 model = TZConvert.IanaToWindows(model);
             } catch (Exception) {
                 model = null;
             }
         }
     }
     return(Task.FromResult(model));
 }
        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);
            }
        }
 /// <summary>
 /// Checks if a config exists, if it doesn't, it creates one
 /// This method should always check if tenant has all configs,
 /// </summary>
 /// <param name="context"></param>
 /// <param name="tenantTimeZone"></param>
 public static void Synchronize(MacheteContext context, string tenantTimeZone)
 {
     foreach (var c in list)
     {
         if (!context.Configs.Any(config => config.key == c.key))
         {
             if (c.key == Cfg.MicrosoftTimeZoneIndex)
             {
                 c.value = TZConvert.IanaToWindows(tenantTimeZone);
             }
             c.datecreated = DateTime.Now;
             c.dateupdated = DateTime.Now;
             c.createdby   = "Init T. Script";
             c.updatedby   = "Init T. Script";
             context.Configs.Add((Config)c.Clone());
             context.SaveChanges();
         }
     }
 }
Beispiel #27
0
        private async Task SheduleStatusChangeAsync(
            DateTime activationDateAndTime,
            TimeSpan durationOfActivity,
            string eventId,
            string eventName,
            Status eventStatus,
            string timeZone)
        {
            var zone             = TimeZoneInfo.FindSystemTimeZoneById(TZConvert.IanaToWindows(timeZone));
            var userLocalTimeNow = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, zone);
            var userTimeToUtc    = userLocalTimeNow.ToUniversalTime();

            var activationDelay = activationDateAndTime - userTimeToUtc;
            var endingDelay     = activationDateAndTime.Add(durationOfActivity) - userTimeToUtc;
            var studentsNames   = await this.GetStudentsNamesByEventIdAsync(eventId);

            if (eventStatus == Status.Active)
            {
                foreach (var name in studentsNames.Distinct())
                {
                    await this.hub.Clients.Group(name).SendAsync("NewActiveEventMessage");
                }

                await this.hub.Clients.Group(GlobalConstants.AdministratorRoleName).SendAsync("ActiveEventUpdate", eventName);

                await this.scheduledJobsService.DeleteJobsAsync(eventId, false);

                await this.scheduledJobsService.CreateEndEventJobAsync(eventId, endingDelay);
            }
            else
            {
                foreach (var name in studentsNames.Distinct())
                {
                    await this.hub.Clients.Group(name).SendAsync("NewPendingEventMessage");
                }

                await this.scheduledJobsService.DeleteJobsAsync(eventId, true);

                await this.scheduledJobsService.CreateStartEventJobAsync(eventId, activationDelay);

                await this.scheduledJobsService.CreateEndEventJobAsync(eventId, endingDelay);
            }
        }
Beispiel #28
0
 public void UpdateAutoTimeZone()
 {
     try
     {
         var tzIana = TimeZoneLookup.GetTimeZone(Convert.ToDouble(Lat.Text), Convert.ToDouble(Long.Text)).Result;
         var tzMs   = TZConvert.IanaToWindows(tzIana);
         var tzInfo = TimeZoneInfo.FindSystemTimeZoneById(tzMs);
         SequenceTimeZone = tzInfo;
         //SequenceTimeZoneOffset = TimeZoneInfo.GetUtcOffset;
         SequenceTimeZoneOffset = GetTZOffset(DateTime.Now, tzInfo);
         //                SequenceTimeZoneOffset = TimeZoneInfo.
         //TimeZoneInfo.FindSystemTimeZoneById(tzMs);
         //offsetFromUtc = TimeZoneInfo.ConvertTimeToUtc(DateTime.UtcNow, tzInfo);
         //Console.WriteLine("{0}", TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tzInfo));
         LocalTimeNowTextBox.Text = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tzInfo).ToString();
         var convertedTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tzInfo);
         TimeZoneTextBlock.Text = tzMs.ToString();
         SiteLat  = Convert.ToDouble(Lat.Text);
         SiteLong = Convert.ToDouble(Long.Text);
     }
     catch { TimeZoneTextBlock.Text = "INVALID"; }
 }
        static void Main(string[] args)
        {
            TimeZoneInfo localZone = TimeZoneInfo.Local; //Getting general information about the local time zone.

            Console.WriteLine("General timezone info: ");
            Console.WriteLine("Standard name is: {0}.", localZone.StandardName);
            Console.WriteLine("Display name is: {0}.", localZone.DisplayName);

            while (true)
            {
                string localDisplay   = localZone.StandardName;
                string olsonDisplay   = TZConvert.WindowsToIana(localDisplay); //Converting the local Windows timezone into Olson time zone.
                string windowsDisplay = TZConvert.IanaToWindows(olsonDisplay); //Taking the converted Olson time zone, and converting it back to Windows time zone display.

                //Converting between Olson time zone and Windows time zone with any key, unless esc is pressed

                Console.WriteLine("\nPress any key to convert to Olson timezone or esc to exit");

                if (Console.ReadKey().Key != ConsoleKey.Escape)
                {
                    PrintOlsonTimeZone(olsonDisplay);
                }
                else
                {
                    break;
                }

                Console.WriteLine("\nPress any key to convert to Windows timezone or esc to exit");

                if (Console.ReadKey().Key != ConsoleKey.Escape)
                {
                    PrintWindowsTimeZone(windowsDisplay);
                }
                else
                {
                    break;
                }
            }
        }
        public void Deserialize(string content)
        {
            // remove heading and trailing white spaces
            content = content.Trim();

            // make sure that the parameter starts with TZID
            if (!content.StartsWith("TZID="))
            {
                throw new ArgumentException("Invalid timezone identifier parameter detected! Property parameter needs to start with TZID keyword!");
            }

            // get the value as string and parse it
            string valueAsString = content.Substring(content.IndexOf('=') + 1).Trim();

            // check if the iana timezone is unique
            IsUniqueId = valueAsString.StartsWith('/');

            // parse timezone info
            string timezoneAsString = IsUniqueId ? valueAsString.Substring(1) : valueAsString;
            string id = TZConvert.IanaToWindows(timezoneAsString);

            Timezone = TimeZoneInfo.FindSystemTimeZoneById(id);
        }