Esempio n. 1
0
        private bool TryParseTimeZone(string timeZone, out TimeZoneInfo tzi)
        {
            tzi = null;
            if (!TZConvert.TryGetTimeZoneInfo(timeZone, out tzi))
            {
                foreach (string tz in TZConvert.KnownIanaTimeZoneNames)
                {
                    if (tz.ToLowerInvariant().Contains(timeZone.ToLowerInvariant()))
                    {
                        tzi = TZConvert.GetTimeZoneInfo(tz);
                        return(true);
                    }
                }

                foreach (string tz in TZConvert.KnownWindowsTimeZoneIds)
                {
                    if (tz.ToLowerInvariant().Contains(timeZone.ToLowerInvariant()))
                    {
                        tzi = TZConvert.GetTimeZoneInfo(tz);
                        return(true);
                    }
                }
                return(false);
            }

            return(true);
        }
Esempio n. 2
0
        /// <param name="languageCode">BCP 47 language code for render the display name of time zones in.</param>
        public static List <TimeZoneInfoViewModel> ListAllSupportedTimeZones()
        {
            // TODO: Refactor this & client so it makes a better selector, ref: https://github.com/moment/moment-timezone/issues/499#issuecomment-305338182

            return(DateTimeZoneProviders.Tzdb
                   .GetAllZones()
                   .Select(tz =>
            {
                TZConvert.TryGetTimeZoneInfo(tz.Id, out var tzi);
                return new
                {
                    tz.Id,
                    tzi,
                };
            })
                   .Where(x => x.tzi != null)
                   .Select(x => new
            {
                x.Id,
                x.tzi.BaseUtcOffset.TotalSeconds,
            })
                   .OrderBy(x => x.TotalSeconds)
                   .Select(x => new TimeZoneInfoViewModel
            {
                Id = x.Id,
                DisplayName = $"{x.Id} {TZNames.GetDisplayNameForTimeZone(x.Id, CultureInfo.CurrentCulture.Name)}",
            })
                   .ToList());
        }
Esempio n. 3
0
        public async Task ValidTimeZone([Summary("The time zone to validate")][Remainder] string timeZone = null)
        {
            await Context.Channel.TriggerTypingAsync();

            _logger.LogInformation("{username}#{discriminator} executed validtimezone ({timezone}) on {server}/{channel}",
                                   Context.User.Username, Context.User.Discriminator, timeZone, Context.Guild?.Name ?? "DM", Context.Channel.Name);

            if (timeZone == null)
            {
                await Context.Channel.SendEmbedAsync("Unable to parse time zone", "Please provide a windows or IANA timezone",
                                                     ColorHelper.GetColor(await _serverService.GetServer(Context.Guild)));

                return;
            }

            TimeZoneInfo tzi;

            if (!TZConvert.TryGetTimeZoneInfo(timeZone, out tzi))
            {
                await Context.Channel.SendEmbedAsync("Invalid Time Zone", $"`{timeZone}` is *not* a valid windows or IANA timezone.",
                                                     ColorHelper.GetColor(await _serverService.GetServer(Context.Guild)));

                return;
            }
            else
            {
                await Context.Channel.SendEmbedAsync("Valid Time Zone", $"`{timeZone}` *is* a valid windows or IANA timezone.",
                                                     ColorHelper.GetColor(await _serverService.GetServer(Context.Guild)));
            }
        }
        /// <summary>
        /// Attempts to retrieve a <see cref="T:System.TimeZoneInfo" /> object given a valid Windows or IANA time zone identifier,
        /// regardless of which platform the application is running on. If it cant find, default it to UTC.
        /// </summary>
        /// <param name="tzTimeZoneId"></param>
        /// <returns></returns>
        public static TimeZoneInfo GetTimeZoneInfo(string tzTimeZoneId)
        {
            var windowsTimeZone = TimeZoneInfo.Utc;

            return(!TZConvert.TryGetTimeZoneInfo(tzTimeZoneId, out var windowsTimeZoneId)
                ? windowsTimeZone
                : windowsTimeZoneId);
        }
Esempio n. 5
0
        public async Task <RuntimeResult> AddAsync(
            [Summary("The date on which the session will take place.")] string date,
            [Summary("The time at which the session will take place.")] string time)
        {
            var campaign = await _campaignService.GetByTextChannelId(Context.Channel.Id);

            if (campaign == null)
            {
                return(GameMasterResult.ErrorResult("you are not in a campaign text channel."));
            }

            var commandIssuer = Context.Guild.GetUser(Context.User.Id);

            if (campaign.GameMaster.User.DiscordId != Context.User.Id && !commandIssuer.GuildPermissions.Administrator)
            {
                return(GameMasterResult.ErrorResult("you do not have permission to add a session to this campaign. You must either be the Game Master of this campaign or a Server Administrator."));
            }

            if (!DateTime.TryParseExact($"{date} {time}", "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out var parsedDate))
            {
                return(GameMasterResult.ErrorResult("you entered an invalid date. Dates must be in the form 'dd/MM/yyyy hh:mm'"));
            }

            var user = await _userService.GetByDiscordUser(Context.User);

            var timeZoneId = user.TimeZoneId;

            if (timeZoneId == null)
            {
                await ReplyAsync("You do not have your timezone set, so I will just assume you wrote that date in UTC. If you want me to account for your timezone, set it using the '!timezone' command.");

                timeZoneId = "UTC";
            }
            if (!TZConvert.TryGetTimeZoneInfo(timeZoneId, out var tzInfo))
            {
                return(GameMasterResult.ErrorResult("your timezone was not found."));
            }

            var utcTime = TimeZoneInfo.ConvertTimeToUtc(parsedDate, tzInfo);

            if (utcTime <= DateTime.UtcNow)
            {
                return(GameMasterResult.ErrorResult("you cannot schedule a session in the past!"));
            }

            try
            {
                var session = await _sessionService.Create(campaign.Id, Schedule.AdHoc, utcTime);
                await ReplyAsync(embed : EmbedBuilder.SessionInfo($"Session successfully added for this campaign.", session));

                return(GameMasterResult.SuccessResult());
            }
            catch (Exception e)
            {
                return(GameMasterResult.ErrorResult(e.Message));
            }
        }
 public FixedPriceService(
     IOptions <FixedPriceOptions> options
     )
 {
     _fixedPrices = GetFixedPrices(options.Value);
     if (!TZConvert.TryGetTimeZoneInfo(options.Value.TimeZone, out _timeZone))
     {
         throw new ArgumentException(nameof(options.Value.TimeZone), $"Invalid TimeZone {options.Value.TimeZone}");
     }
 }
Esempio n. 7
0
        static void Main1(string[] args)
        {
            TimeZoneInfo info = null;

            foreach (var item in TimeZoneInfo.GetSystemTimeZones())
            {
                if (TZConvert.TryGetTimeZoneInfo(item.DisplayName, out info))
                {
                    Console.WriteLine(item.DisplayName);
                }
            }
        }
Esempio n. 8
0
 private static TimeZoneInfo JstTimeZoneInfo()
 {
     if (TZConvert.TryGetTimeZoneInfo("Asia/Tokyo", out var timezoneInfo))
     {
         return(timezoneInfo);
     }
     else
     {
         // Emergency fallback
         return(TimeZoneInfo.CreateCustomTimeZone("JST", new TimeSpan(9, 0, 0), "(GMT+09:00) JST", "JST"));
     }
 }
Esempio n. 9
0
        public static DateTime ToLocalTime(this DateTime utcDate, string ianaTimezone)
        {
            utcDate.GuardAgainstInvalid(d => d != DateTime.MinValue, nameof(utcDate));
            utcDate.GuardAgainstInvalid(d => d.Kind == DateTimeKind.Utc, nameof(utcDate),
                                        Resources.DateTimeExtensions_DateTimeIsNotUtc);
            ianaTimezone.GuardAgainstNull(nameof(ianaTimezone));

            if (!TZConvert.TryGetTimeZoneInfo(ianaTimezone, out var timeZoneInfo))
            {
                throw new ArgumentOutOfRangeException(Resources.DateTimeExtensions_InvalidTimezone);
            }

            return(TimeZoneInfo.ConvertTimeFromUtc(utcDate, timeZoneInfo));
        }
Esempio n. 10
0
        public async Task <Result> UpdateUserPreferences(Models.User user, UserPreferencesDto newPreferences)
        {
            TimeZoneInfo info;
            var          validTimeZone = TZConvert.TryGetTimeZoneInfo(newPreferences.IanaTimezone, out info);

            if (!validTimeZone)
            {
                return(Results.Fail("Invalid time zone"));
            }

            user.IanaTimezone = newPreferences.IanaTimezone;
            await _context.SaveChangesAsync();

            return(Results.Ok());
        }
Esempio n. 11
0
        private static bool TryGetTimeZoneInfo(string ianaOrWindowsTimeZoneId, out TimeZoneInfo timeZoneInfo)
        {
            if (!TZConvert.TryGetTimeZoneInfo(ianaOrWindowsTimeZoneId, out timeZoneInfo))
            {
                if (!string.IsNullOrWhiteSpace(ianaOrWindowsTimeZoneId) &&
                    ianaOrWindowsTimeZoneId == CoordinatedUniversalTime ||
                    ianaOrWindowsTimeZoneId == TimeZoneInfo.Utc.StandardName)
                {
                    timeZoneInfo = TimeZoneInfo.Utc;
                    return(true);
                }

                return(false);
            }

            return(true);
        }
Esempio n. 12
0
        public static ValueTask <FluidValue> ChangeTimeZone(FluidValue input, FilterArguments arguments, TemplateContext context)
        {
            if (!TryGetDateTimeInput(input, context, out var value))
            {
                return(NilValue.Instance);
            }

            if (arguments.At(0).IsNil())
            {
                return(NilValue.Instance);
            }

            var timeZone = arguments.At(0).ToStringValue();

            if (!TZConvert.TryGetTimeZoneInfo(timeZone, out var timeZoneInfo))
            {
                return(new DateTimeValue(value));
            }

            var result = TimeZoneInfo.ConvertTime(value, timeZoneInfo);

            return(new DateTimeValue(result));
        }
Esempio n. 13
0
 /// <summary>
 ///     Support find time zone id by difference platform: Windows, Mac, Linux.
 /// </summary>
 /// <param name="timeZoneId">  </param>
 /// <param name="timeZoneInfo"></param>
 /// <returns></returns>
 public static bool TryGetTimeZoneInfo(string timeZoneId, out TimeZoneInfo timeZoneInfo)
 {
     return(TZConvert.TryGetTimeZoneInfo(timeZoneId, out timeZoneInfo));
 }
Esempio n. 14
0
 public bool TimeZoneExists(string name)
 {
     return(TZConvert.TryGetTimeZoneInfo(name, out _));
 }
 /// <summary>
 /// Validate a Timezone
 /// </summary>
 /// <param name="timezone"></param>
 /// <returns></returns>
 public static bool ValidTimezone(string timezone)
 {
     return(TZConvert.TryGetTimeZoneInfo(timezone, out _));
 }
Esempio n. 16
0
        public async Task <RuntimeResult> ScheduleAsync(
            [Summary("The date on which the session will take place.")] string date,
            [Summary("The time at which the session will take place.")] string time,
            [Summary("The schedule type for the session.")] string schedule)
        {
            var campaign = await _campaignService.GetByTextChannelId(Context.Channel.Id);

            if (campaign == null)
            {
                return(GameMasterResult.ErrorResult("you are not in a campaign text channel."));
            }

            // Check to make sure that this user is the game master of the campaign
            var commandIssuer = Context.Guild.GetUser(Context.User.Id);

            if (campaign.GameMaster.User.DiscordId != Context.User.Id && !commandIssuer.GuildPermissions.Administrator)
            {
                return(GameMasterResult.ErrorResult("you do not have permission to schedule a session for this campaign. You must either be the Game Master of this campaign or a Server Administrator."));
            }

            if (!DateTime.TryParseExact($"{date} {time}", "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out var parsedDate))
            {
                return(GameMasterResult.ErrorResult("you entered an invalid date. Dates must be in the form 'dd/MM/yyyy hh:mm'"));
            }

            var user = await _userService.GetByDiscordUser(Context.User);

            var timeZoneId = user.TimeZoneId;

            if (timeZoneId == null)
            {
                await ReplyAsync("You do not have your timezone set, so I will just assume you wrote that date in UTC. If you want me to account for your timezone, set it using the '!set-timezone' command.");

                timeZoneId = "UTC";
            }
            if (!TZConvert.TryGetTimeZoneInfo(timeZoneId, out var tzInfo))
            {
                return(GameMasterResult.ErrorResult("your timezone was not found."));
            }
            var utcTime = TimeZoneInfo.ConvertTimeToUtc(parsedDate, tzInfo);

            if (utcTime <= DateTime.UtcNow)
            {
                return(GameMasterResult.ErrorResult("you cannot schedule a session in the past!"));
            }

            var      scheduleLower = schedule.ToLower();
            Schedule scheduleValue;

            switch (scheduleLower)
            {
            case "weekly":
                scheduleValue = Schedule.Weekly;
                break;

            case "fortnightly":
                scheduleValue = Schedule.Fortnightly;
                break;

            case "monthly":
                scheduleValue = Schedule.Monthly;
                break;

            default:
                return(GameMasterResult.ErrorResult("you chose an invalid schedule type. Choose from 'Weekly', 'Fortnightly', or 'Monthly'."));
            }

            try
            {
                var session = await _sessionService.Create(campaign.Id, scheduleValue, utcTime);
                await ReplyAsync(embed : EmbedBuilder.SessionInfo($"Session scheduled for this campaign.", session));

                return(GameMasterResult.SuccessResult());
            }
            catch (Exception e)
            {
                return(GameMasterResult.ErrorResult(e.Message));
            }
        }
Esempio n. 17
0
 // find the timezone info for given id string
 public static TimeZoneInfo IDToTimezone(string id)
 {
     TZConvert.TryGetTimeZoneInfo(id, out TimeZoneInfo t);
     return(t);
 }