public void SetData(EventProfile item, List <string> events) { string lang = CultureInfo.CurrentCulture.Name; var abbreviations = TZNames.GetAbbreviationsForTimeZone(item.TimezoneId, lang); string lblTimeZone = abbreviations.Standard; DateTime eventDate = ConvertToUTC(item.DateOfEventUtc, item.TimezoneId); lblSportName.Text = item.SportName; lblDate.Text = eventDate.ToString("h:mm tt") + " " + lblTimeZone; lblTeam1.Text = item.Team1Name; lblTeam2.Text = item.Team2Name; lblEventName.Text = item.Name; team1Task?.Cancel(item.Team1Url); if (!string.IsNullOrEmpty(item.Team1Url)) { team1Task = new ImageLoaderHelper(item.Team1Url, imgTeam1, "DefaultProfile"); } team2Task?.Cancel(item.Team2Url); if (!string.IsNullOrEmpty(item.Team2Url)) { team2Task = new ImageLoaderHelper(item.Team2Url, imgTeam2, "DefaultProfile"); } if (events.Contains(item.Id)) { imgTagged.Image = UIImage.FromBundle("IconChecked"); } else { imgTagged.Image = UIImage.FromBundle("IconUnchecked"); } if (item.TeamCount == 2) { vwTeam1.Hidden = false; vwTeam2.Hidden = false; vwEventName.Hidden = true; } else { vwTeam1.Hidden = true; vwTeam2.Hidden = true; vwEventName.Hidden = false; } }
public IDictionary <string, string> Get(string country, DateTimeOffset?threshold) { var languageCode = CultureInfo.CurrentUICulture.Name; if (country != null) { return(GetTimeZonesForCountry(country, threshold, languageCode)); } return(TZNames.GetCountryNames(languageCode) .SelectMany(x => GetTimeZonesForCountry(x.Key, threshold, languageCode) .Select(y => new { CountryCode = x.Key, Country = x.Value, TimeZoneId = y.Key, TimeZoneName = y.Value })) .GroupBy(x => x.TimeZoneId) .ToDictionary(x => x.Key, x => $"{x.First().Country} - {x.First().TimeZoneName}")); }
public void Can_Get_DisplayName_For_Every_Windows_Zone() { var errors = new List <string>(); foreach (string id in TZConvert.KnownWindowsTimeZoneIds) { string displayName = TZNames.GetDisplayNameForTimeZone(id, "en"); if (string.IsNullOrEmpty(displayName)) { errors.Add(id); } } Assert.Empty(errors); }
public static async void SendEmbed(bool successful, List <ValorantEvent> jsonParsed, int counter, SocketTextChannel _socketTextChannel, DiscordSocketClient _client, List <RestUserMessage> messageIDs) { var currentTime = DateTime.Now.ToLongTimeString(); var currentTimeZone = TZNames.GetAbbreviationsForTimeZone(TimeZoneInfo.Local.Id, "en-GB").Standard; var embedBuilder = new EmbedBuilder(); var region = jsonParsed[0].Regions[counter]; ulong guildID = ulong.Parse(Startup._configuration["guild_id"]); ulong channelID = ulong.Parse(Startup._configuration["channel_id"]); _socketTextChannel = _client.GetGuild(guildID).GetTextChannel(channelID); if (successful) { embedBuilder = new EmbedBuilder { Title = $"{region.Name.ToUpper()} Maintenance Status:", Color = Color.Green, Description = "There is no scheduled Maintenance!" }; embedBuilder.WithFooter($"Trexia A1.0 | Updated on {currentTime} {currentTimeZone}"); var unsuccessfulEmbed = await _socketTextChannel.SendMessageAsync(String.Empty, false, embedBuilder.Build()); messageIDs.Add(unsuccessfulEmbed); } else { embedBuilder = new EmbedBuilder { Title = $"{region.Name.ToUpper()} Maintenance Status:", Color = Color.Red }; if (region.Maintenances[0].MaintenanceStatus.Equals("scheduled")) { embedBuilder.AddField("Status:", "Scheduled Maintenance", false); } embedBuilder.AddField("Description:", region.Maintenances[0].Updates[0].Description, false); embedBuilder.WithFooter($"Trexia A1.0 | Updated on {currentTime} {currentTimeZone}"); var unsuccessfulEmbed = await _socketTextChannel.SendMessageAsync(String.Empty, false, embedBuilder.Build()); messageIDs.Add(unsuccessfulEmbed); } }
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")); }
public void Can_Get_DisplayName_For_Every_Mappable_IANA_Zone() { string[] unmappableZones = { "Antarctica/Troll" }; var errors = new List <string>(); foreach (string id in TZConvert.KnownIanaTimeZoneNames.Except(unmappableZones)) { string displayName = TZNames.GetDisplayNameForTimeZone(id, "en"); if (string.IsNullOrEmpty(displayName)) { errors.Add(id); } } Assert.Empty(errors); }
public async Task WeatherAsync([Remainder] string zone) { IList <(Weather, DateTime)> forecast; try { forecast = Weather.GetForecast(zone, count: 10); } catch (ArgumentException) { await ReplyAsync("The specified zone could not be found."); return; } var(currentWeather, currentWeatherStartTime) = forecast[0]; var dbUser = Db.Users.FirstOrDefault(u => u.DiscordId == Context.User.Id); var(customTzi, _) = Util.GetLocalizedTimeForUser(dbUser, DateTime.Now); var tzi = customTzi ?? TimeZoneInfo.FindSystemTimeZoneById(Util.PtIdString()); var tzAbbrs = TZNames.GetAbbreviationsForTimeZone(tzi.Id, "en-US"); var tzAbbr = tzi.IsDaylightSavingTime(DateTime.Now) ? tzAbbrs.Daylight : tzAbbrs.Standard; var formattedForecast = $"**Current:** {currentWeather.Name} (Began at {TimeZoneInfo.ConvertTimeFromUtc(currentWeatherStartTime, tzi).ToShortTimeString()} {tzAbbr})"; foreach (var(weather, startTime) in forecast.Skip(1)) { var zonedTime = TimeZoneInfo.ConvertTimeFromUtc(startTime, tzi); formattedForecast += $"\n{zonedTime.ToShortTimeString()}: {weather.Name}"; } var embed = new EmbedBuilder() .WithAuthor(new EmbedAuthorBuilder() .WithIconUrl($"https://www.garlandtools.org/files/icons/weather/{currentWeather.Name.ToString().Replace(" ", "%20")}.png") .WithName($"Current weather for {Util.JadenCase(zone)}:")) .WithTitle($"Next weather starts in {Math.Truncate((forecast[1].Item2 - DateTime.UtcNow).TotalMinutes)} minutes.") .WithColor(Color.LightOrange) .WithDescription(formattedForecast) .Build(); await ReplyAsync(embed : embed); }
public void FortWayneChristmas() { const string dateTime = "2017-12-25 20:30:40"; var timeZone = TimeZoneLookup.GetTimeZone(40.977506, -85.196059).Result; timeZone.Should().Be("America/Indiana/Indianapolis"); var abbreviation = TZNames.GetAbbreviationsForTimeZone(timeZone, "en-US").Generic; abbreviation.Should().Be("ET"); var pattern = LocalDateTimePattern.CreateWithInvariantCulture("yyyy-MM-dd HH:mm:ss"); var ldt = pattern.Parse(dateTime).Value; var zdt = ldt.InZoneLeniently(DateTimeZoneProviders.Tzdb[timeZone]); var date = zdt.ToDateTimeOffset(); date.ShouldBeEquivalentTo(new DateTimeOffset(2017, 12, 25, 20, 30, 40, TimeSpan.FromHours(-5))); Console.WriteLine(date.ToString("s")); }
public static DateTime InTimeZone(this DateTime nowTime, string timezoneName) { var names = TZNames.GetNamesForTimeZone(timezoneName, "en-US"); TimeZoneInfo timezone; try { timezone = TimeZoneInfo.FindSystemTimeZoneById(names.Standard); } catch (TimeZoneNotFoundException e) { timezone = TimeZoneInfo.FindSystemTimeZoneById(timezoneName); } return(TimeZoneInfo.ConvertTimeFromUtc(nowTime, timezone)); }
public static async void EditEmbed(bool successful, List <ValorantEvent> jsonParsed, int counter, RestUserMessage message) { var currentTime = DateTime.Now.ToLongTimeString(); var currentTimeZone = TZNames.GetAbbreviationsForTimeZone(TimeZoneInfo.Local.Id, "en-GB").Standard; var region = jsonParsed[0].Regions[counter]; var embedBuilder = new EmbedBuilder(); if (successful) { embedBuilder = new EmbedBuilder { Title = $"{jsonParsed[0].Regions[counter].Name.ToUpper()} Maintenance Status:", Color = Color.Green, Description = "There is no scheduled Maintenance!" }; embedBuilder.WithFooter($"Trexia A1.0 | Updated on {currentTime} {currentTimeZone}"); await message.ModifyAsync(m => { m.Embed = embedBuilder.Build(); }); } else { embedBuilder = new EmbedBuilder { Title = $"{region.Name.ToUpper()} Maintenance Status:", Color = Color.Red }; if (region.Maintenances[0].MaintenanceStatus.Equals("scheduled")) { embedBuilder.AddField("Status:", "Scheduled Maintenance", false); } embedBuilder.AddField("Description:", jsonParsed[0].Regions[counter].Maintenances[0].Updates[0].Description, false); embedBuilder.WithFooter($"Trexia A1.0 | Updated on {currentTime} {currentTimeZone}"); await message.ModifyAsync(m => { m.Embed = embedBuilder.Build(); }); } }
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"); }
private static string GetTimeZoneAbbreviation(DateTime timeZoneTime, TimeZoneInfo tz) { // Get abbreviated timezone name TimeZoneValues abbr = TZNames.GetAbbreviationsForTimeZone(tz.Id, "en-au"); // Handling for things without abbreviations switch (abbr.Standard) { case "Japan Standard Time": abbr.Standard = "JST"; break; default: break; } // Check if daylight savings applies return(tz.IsDaylightSavingTime(timeZoneTime) ? abbr.Daylight : abbr.Standard); }
//create the dropdown list for selecting time zone public static List <SelectListItem> GetTimeZones() { List <SelectListItem> timeZonesList = new List <SelectListItem>(); SelectListItem s = new SelectListItem(); //start with a double dash for default no selection s.Text = "--"; timeZonesList.Add(s); bool isPresent = false; foreach (var id in DateTimeZoneProviders.Tzdb.Ids) { SelectListItem l = new SelectListItem(); if (timeZonesList.Count == 1) { l.Text = DateTimeZoneProviders.Tzdb[id].ToString() + " - " + TZNames.GetNamesForTimeZone(id, "en-US").Generic; timeZonesList.Add(l); } //check if the name has already been entered else if (timeZonesList.Count >= 2) { for (int i = 1; i < timeZonesList.Count; i++) { if (timeZonesList[i].Text.Contains("-") && timeZonesList[i].Text. Substring(0, timeZonesList[i].Text.IndexOf("-")) .Equals(TZNames.GetNamesForTimeZone(id, "en-US").Generic)) { isPresent = true; } } if (!isPresent) { l.Text = DateTimeZoneProviders.Tzdb[id].ToString() + " - " + TZNames.GetNamesForTimeZone(id, "en-US").Generic; timeZonesList.Add(l); } isPresent = false; } } return(timeZonesList); }
/// <summary> /// Lookup short time zone abbreviation from geo coordinates. /// </summary> /// <param name="geoPoint"></param> /// <returns>ET,CT,MT,PT</returns> public static string LookupTimeZoneLabel(this GeoPoint geoPoint) { if (geoPoint == null || Math.Abs(geoPoint.Latitude) < .0001) { return(null); } try { var timeZone = GetTimeZone(geoPoint); var abbreviations = TZNames.GetAbbreviationsForTimeZone(timeZone, "en-US"); return(abbreviations.Generic); // == "PT" } catch (Exception e) { Logger.WarnFormat("Unable to look up timezone for ({0},{1}). {2}", geoPoint.Latitude, geoPoint.Longitude, e.RecursiveErrorMessage()); return(null); } }
public void Can_Get_TimeZones_For_All_Countries_EN_AllZones() { var locale = "en-US"; var countries = TZNames.GetCountryNames(locale); foreach (var country in countries) { _output.WriteLine("{0} : {1}", country.Key, country.Value); _output.WriteLine("------------------------------------------------------------"); var zones = TZNames.GetTimeZonesForCountry(country.Key, locale); //Assert.NotEmpty(zones); foreach (var zone in zones) { _output.WriteLine($"{zone.Value.PadRight(50)} {zone.Key}"); } _output.WriteLine(""); } }
public void Can_Get_TimeZones_For_All_Countries_EN_AllZones() { var locale = "en-US"; IDictionary <string, string> countries = TZNames.GetCountryNames(locale); foreach ((string countryCode, string countryDisplayName) in countries) { _output.WriteLine("{0} : {1}", countryCode, countryDisplayName); _output.WriteLine("------------------------------------------------------------"); IDictionary <string, string> zones = TZNames.GetTimeZonesForCountry(countryCode, locale); //Assert.NotEmpty(zones); foreach ((string zoneName, string zoneDisplayName) in zones) { _output.WriteLine($"{zoneDisplayName,-50} {zoneName}"); } _output.WriteLine(""); } }
public void Can_Get_Names_For_UTC_All_Langs() { ICollection <string> langs = TZNames.GetLanguageCodes(); var ok = true; foreach (string lang in langs) { try { string name = TZNames.GetNamesForTimeZone("UTC", lang).Generic; _output.WriteLine($"{lang,-10} => {name}"); } catch { ok = false; _output.WriteLine($"{lang,-10} => FAIL!!!!!!!!!!!!!!!"); } } Assert.True(ok); }
public void Can_Get_Names_For_UTC_All_Langs() { var langs = TZNames.GetLanguageCodes(); var ok = true; foreach (var lang in langs) { try { var name = TZNames.GetNamesForTimeZone("UTC", lang).Generic; _output.WriteLine($"{lang.PadRight(10)} => {name}"); } catch { ok = false; _output.WriteLine($"{lang.PadRight(10)} => FAIL!!!!!!!!!!!!!!!"); } } Assert.True(ok); }
public void Can_Get_Country_And_City_For_All_Zones_In_All_Countries() { var locale = "en-US"; var countries = TZNames.GetCountryNames(locale); foreach (var country in countries) { _output.WriteLine("{0} : {1}", country.Key, country.Value); _output.WriteLine("------------------------------------------------------------"); var zones = TZNames.GetTimeZoneIdsForCountry(country.Key); foreach (var zone in zones) { var names = TZNames.GetLocationNamesForTimeZone(zone, locale); _output.WriteLine($"{zone.PadRight(30)} {string.Join(",",names.Countries).PadRight(30)} {names.City.PadRight(30)}"); Assert.Contains(country.Value, names.Countries); } _output.WriteLine(""); } }
public void TucsonChristmas() { const string dateTime = "2017-12-25 20:30:40"; var timeZone = TimeZoneLookup.GetTimeZone(32.114510, -110.939259).Result; timeZone.Should().Be("America/Phoenix"); var abbreviation = TZNames.GetAbbreviationsForTimeZone(timeZone, "en-US").Generic; abbreviation.Should().Be("MT"); var pattern = LocalDateTimePattern.CreateWithInvariantCulture("yyyy-MM-dd HH:mm:ss"); var ldt = pattern.Parse(dateTime).Value; var zdt = ldt.InZoneLeniently(DateTimeZoneProviders.Tzdb[timeZone]); var date = zdt.ToDateTimeOffset(); date.ShouldBeEquivalentTo(new DateTimeOffset(2017, 12, 25, 20, 30, 40, TimeSpan.FromHours(-7))); var s = date.ToString("yyyy-MM-ddTHH\\:mm\\:sszzz"); Console.WriteLine(s); s.Should().Be("2017-12-25T20:30:40-07:00"); }
public async Task OnReactionAdd(Cacheable <IUserMessage, ulong> cmessage, ISocketMessageChannel ichannel, SocketReaction reaction) { if (!(reaction.Emote is Emoji emoji) || emoji.Name != "📳" || !(ichannel is SocketGuildChannel channel)) { return; } var run = _db.Events.FirstOrDefault(e => e.MessageId3 == cmessage.Id); if (run == null || run.Notified || run.RunTime < DateTime.Now.ToBinary() || run.SubscribedUsers.Contains(reaction.UserId.ToString()) || reaction.UserId == run.LeaderId || reaction.UserId == _client.CurrentUser.Id) { return; } await _db.AddMemberToEvent(run, reaction.UserId); var leader = channel.GetUser(run.LeaderId); var member = _client.GetUser(reaction.UserId); var runTime = DateTime.FromBinary(run.RunTime); var dbUser = _db.Users.FirstOrDefault(u => u.DiscordId == member.Id); // ReSharper disable once JoinDeclarationAndInitializer TimeZoneInfo tzi; var(customTzi, localizedRunTime) = Util.GetLocalizedTimeForUser(dbUser, runTime); tzi = customTzi ?? TimeZoneInfo.FindSystemTimeZoneById("America/Los_Angeles"); if (localizedRunTime != default) { runTime = localizedRunTime; runTime = runTime.AddHours(8); } var tzAbbrs = TZNames.GetAbbreviationsForTimeZone(tzi.Id, "en-US"); var tzAbbr = tzi.IsDaylightSavingTime(DateTime.Now) ? tzAbbrs.Daylight : tzAbbrs.Standard; await member.SendMessageAsync($"You have RSVP'd for {leader.Nickname ?? leader.Username}'s run on on {runTime.DayOfWeek} at {runTime.ToShortTimeString()} ({tzAbbr}) [{runTime.DayOfWeek}, {(Month)runTime.Month} {runTime.Day}]! :thumbsup:"); Log.Information("Added member {MemberId} to run {MessageId}.", reaction.UserId, run.MessageId3); }
public void Can_Get_Zones_For_US() { var zones = TZNames.GetTimeZoneIdsForCountry("US", DateTimeOffset.Now); foreach (var zone in zones) { _output.WriteLine(zone); } var expected = new[] { "Pacific/Honolulu", "America/Adak", "America/Anchorage", "America/Los_Angeles", "America/Phoenix", "America/Denver", "America/Chicago", "America/New_York" }; Assert.Equal(expected, zones); }
public async Task WeatherReportAsync([Remainder] string zone) { IList <(Weather, DateTime)> forecast; try { forecast = Weather.GetForecast(zone, count: 200); } catch (ArgumentException) { await ReplyAsync("The specified zone could not be found."); return; } var dbUser = Db.Users.FirstOrDefault(u => u.DiscordId == Context.User.Id); var(customTzi, _) = Util.GetLocalizedTimeForUser(dbUser, DateTime.Now); var tzi = customTzi ?? TimeZoneInfo.FindSystemTimeZoneById(Util.PtIdString()); var tzAbbrs = TZNames.GetAbbreviationsForTimeZone(tzi.Id, "en-US"); var tzAbbr = tzi.IsDaylightSavingTime(DateTime.Now) ? tzAbbrs.Daylight : tzAbbrs.Standard; var outputData = forecast .Aggregate($"Time\t\t\t\tWeather\n{new string('=', "7/4/2021 6:13:20 PM PDT Dust Storms".Length)}", (agg, next) => { var(weather, startTime) = next; var zonedTime = TimeZoneInfo.ConvertTimeFromUtc(startTime, tzi); var timeText = zonedTime + " " + tzAbbr; return(agg + $"\n{timeText}{(timeText.Length < 24 ? "\t" : "")}\t{weather.Name}"); }); await using var file = new MemoryStream(Encoding.UTF8.GetBytes(outputData)); await Context.Channel.SendFileAsync(file, "weather.txt", messageReference : new MessageReference(Context.Message.Id)); }
public void TestTimeZoneAbbreviations() { string timeZoneId = "Eastern Standard Time"; TimeZoneInfo timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId); Assert.IsNotNull(timeZoneInfo); Assert.AreEqual(timeZoneId, timeZoneInfo.Id); string cultureName = CultureInfo.CurrentCulture.Name; Assert.AreEqual("en-US", cultureName); TimeZoneValues abbreviations = TZNames.GetAbbreviationsForTimeZone(timeZoneId, cultureName); Assert.AreEqual("ET", abbreviations.Generic); Assert.AreEqual("EST", abbreviations.Standard); Assert.AreEqual("EDT", abbreviations.Daylight); TimeZoneValues names = TZNames.GetNamesForTimeZone(timeZoneId, cultureName); Assert.AreEqual("Eastern Time", names.Generic); Assert.AreEqual(timeZoneId, names.Standard); Assert.AreEqual("Eastern Daylight Time", names.Daylight); }
public async Task <IActionResult> OnGetAsync(int?id) { if (id.HasValue) { Title = "Edit"; ChannelId = id.Value; bool exists = await _context.Channels.AnyAsync(m => m.Id == id); if (!exists) { return(NotFound()); } } else { Title = "Create"; ChannelId = -1; } Countries = TZNames.GetCountryNames(CultureInfo.CurrentUICulture.Name) .Select(x => new SelectListItem(x.Value, x.Key)); return(Page()); }
public void Can_Get_Names_For_All_Countries() { IEnumerable <string> countries = CultureInfo.GetCultures(CultureTypes.SpecificCultures) .Select(x => new RegionInfo(x.LCID).TwoLetterISORegionName) .Where(x => !string.IsNullOrEmpty(x)) .Where(x => x.Length == 2) .OrderBy(x => x) .Distinct(); foreach (string country in countries) { try { IDictionary <string, string> zones = TZNames.GetTimeZonesForCountry(country, "en"); _output.WriteLine(country + ": " + zones.Count); Assert.NotEqual(0, zones.Count); } catch { _output.WriteLine(country + " -- FAILED"); throw; } } }
public static void SeedZones(FCTContext _context, ILogger <DictionarySeeder> logger) { logger.LogInformation("DB Seeder: Zones", DateTime.Now); if (_context.Zone.Any()) { return; } var zonesFilePath = Path.Combine(AppContext.BaseDirectory, "LoadData\\zone.csv"); var _createdCountries = _context.Country.ToList(); var zoneList = new List <Zone>(); using (var reader = new StreamReader(zonesFilePath)) using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture)) { csv.Configuration.HasHeaderRecord = false; var records = csv.GetRecords <ZoneModel>(); foreach (var record in records) { zoneList.Add(new Zone() { CountryCode = record.CountryCode, ZoneName = record.ZoneName, GenericZoneName = TZNames.GetNamesForTimeZone(record.ZoneName, "en-US").Generic, Country = _createdCountries.Where(c => c.Alpha2Code == record.CountryCode).FirstOrDefault() }); } _context.AddRange(zoneList); _context.SaveChanges(); } }
public async Task WeatherAsync([Remainder] string zone) { if (Context.Guild != null && Context.Guild.Id == SpecialGuilds.CrystalExploratoryMissions) { const ulong speculation = 738899820168740984; const ulong theorycrafting = 593815337980526603; if (Context.Channel.Id == speculation || Context.Channel.Id == theorycrafting) { await Context.Message.DeleteAsync(); var reply = await ReplyAsync("That command is disabled in this channel."); await Task.Delay(10000); await reply.DeleteAsync(); return; } } IList <(Weather, DateTime)> forecast; try { forecast = Weather.GetForecast(zone, count: 10); } catch (ArgumentException) { await ReplyAsync("The specified zone could not be found."); return; } var(currentWeather, currentWeatherStartTime) = forecast[0]; var dbUser = Db.Users.FirstOrDefault(u => u.DiscordId == Context.User.Id); // ReSharper disable once JoinDeclarationAndInitializer TimeZoneInfo tzi; var(customTzi, _) = Util.GetLocalizedTimeForUser(dbUser, DateTime.Now); tzi = customTzi ?? TimeZoneInfo.FindSystemTimeZoneById(Util.PstIdString()); var tzAbbrs = TZNames.GetAbbreviationsForTimeZone(tzi.Id, "en-US"); var tzAbbr = tzi.IsDaylightSavingTime(DateTime.Now) ? tzAbbrs.Daylight : tzAbbrs.Standard; var formattedForecast = $"**Current:** {currentWeather} (Began at {TimeZoneInfo.ConvertTimeFromUtc(currentWeatherStartTime, tzi).ToShortTimeString()} {tzAbbr})"; foreach (var(weather, startTime) in forecast.Skip(1)) { var zonedTime = TimeZoneInfo.ConvertTimeFromUtc(startTime, tzi); formattedForecast += $"\n{zonedTime.ToShortTimeString()}: {weather}"; } var embed = new EmbedBuilder() .WithAuthor(new EmbedAuthorBuilder() .WithIconUrl($"https://www.garlandtools.org/files/icons/weather/{currentWeather.GetName().Replace(" ", "%20")}.png") .WithName($"Current weather for {Util.JadenCase(zone)}:")) .WithTitle($"Next weather starts in {Math.Truncate((forecast[1].Item2 - DateTime.UtcNow).TotalMinutes)} minutes.") .WithColor(Color.LightOrange) .WithDescription(formattedForecast) .Build(); await ReplyAsync(embed : embed); }
void GetData() { DateTime eventDate = DateTime.Now; var apiTask = new ServiceApi().GetEventProfile(EventId); apiTask.HandleError(); apiTask.OnSucess(response => { this.profile = response.Result; lblTitle.Text = response.Result.Name; lblSport.Text = response.Result.SportName; lblLocation.Text = response.Result.Location; eventDate = ConvertToUTC(response.Result.DateOfEventUtc, response.Result.TimezoneId); lblDate.Text = eventDate.ToString("D"); if (response.Result.IsTbd) { lblTime.Text = "TBD"; } else { string lang = CultureInfo.CurrentCulture.Name; var abbreviations = TZNames.GetAbbreviationsForTimeZone(response.Result.TimezoneId, lang); lblTime.Text = eventDate.ToString("h:mm tt") + " " + abbreviations.Standard; } lblName.Text = response.Result.Name; lblEventName.Text = profile.Name; if (!string.IsNullOrEmpty(profile.Team1Url)) { ImageService.Instance.LoadUrl(profile.Team1Url).Retry(3, 300).Into(imgTeam1); } if (!string.IsNullOrEmpty(profile.Team2Url)) { ImageService.Instance.LoadUrl(profile.Team2Url).Retry(3, 300).Into(imgTeam2); } lblTeam1Name.Text = profile.Team1Name; lblTeam2Name.Text = profile.Team2Name; imgRight.UserInteractionEnabled = true; if (string.IsNullOrEmpty(profile.TicketUrl)) { imgRight.Hidden = true; } if (profile.DateOfEventUtc <= DateTime.UtcNow) { if (profile.TeamCount == 2) { lcRightWidth.Constant = 0; } else { imgRight.Hidden = false; } imgRight.Image = null; if (!string.IsNullOrEmpty(profile.WinningTeamUrl)) { ImageService.Instance.LoadUrl(profile.WinningTeamUrl).Retry(3, 300).Into(imgRight); } imgRight.UserInteractionEnabled = false; } var boldAttributes = new UIStringAttributes(); boldAttributes.Font = UIFont.BoldSystemFontOfSize(btnShowTeams.Font.PointSize); boldAttributes.ForegroundColor = UIColor.FromRGB(144, 144, 144); var regularAttributes = new UIStringAttributes(); regularAttributes.Font = UIFont.SystemFontOfSize(btnShowTeams.Font.PointSize); regularAttributes.ForegroundColor = UIColor.FromRGB(144, 144, 144); NSMutableAttributedString attributedString = new NSMutableAttributedString("Show me all ", regularAttributes); attributedString.Append(new NSMutableAttributedString(profile.TeamCount.ToString() + " teams", boldAttributes)); btnShowTeams.SetAttributedTitle(attributedString, UIControlState.Normal); if (profile.TeamCount == 2) { vwTwoTeams.Hidden = false; vwManyTeams.Hidden = true; } else { vwTwoTeams.Hidden = true; vwManyTeams.Hidden = false; } lblPosts.Text = LargeValueHelper.GetString(response.Result.Posts); lblTeam1Score.Text = response.Result.Team1Score; lblTeam2Score.Text = response.Result.Team2Score; }); }
private static IDictionary <string, string> GetTimeZonesForCountry(string country, DateTimeOffset?threshold, string languageCode) { return(threshold == null ? TZNames.GetTimeZonesForCountry(country, languageCode) : TZNames.GetTimeZonesForCountry(country, languageCode, threshold.Value)); }