Esempio n. 1
0
        public TimeZoneController(
            IClock clock,
            IDateTimeZoneProvider dateTimeZoneProvider,
            TzdbDateTimeZoneSource dateTimeZoneSource)
            : base(clock, dateTimeZoneProvider)
        {
            var now = clock.GetCurrentInstant();

            foreach (var temp in dateTimeZoneSource.ZoneLocations)
            {
                var timeZone     = dateTimeZoneProvider.GetZoneOrNull(temp.ZoneId);
                var zoneInterval = timeZone.GetZoneInterval(now);
                var offset       = zoneInterval.WallOffset;

                if (timeZone != null)
                {
                    timeZones.Add(new TimeZoneInformation
                    {
                        Id     = timeZone.Id,
                        Name   = zoneInterval.Name,
                        Offset = offset.ToTimeSpan().Hours
                    });
                }
            }
        }
Esempio n. 2
0
        public DateTime ConvertToLocalTime(DateTime utcDateTime, string timeZoneId)
        {
            DateTime dUtc;

            switch (utcDateTime.Kind)
            {
            case DateTimeKind.Utc:
                dUtc = utcDateTime;
                break;

            case DateTimeKind.Local:
                dUtc = utcDateTime.ToUniversalTime();
                break;

            default:     //DateTimeKind.Unspecified
                dUtc = DateTime.SpecifyKind(utcDateTime, DateTimeKind.Utc);
                break;
            }

            var timeZone = tzSource.GetZoneOrNull(timeZoneId);

            if (timeZone == null)
            {
                if (log != null)
                {
                    log.LogWarning("failed to find timezone for " + timeZoneId);
                }

                return(utcDateTime);
            }

            var instant = Instant.FromDateTimeUtc(dUtc);
            var zoned   = new ZonedDateTime(instant, timeZone);

            return(new DateTime(
                       zoned.Year,
                       zoned.Month,
                       zoned.Day,
                       zoned.Hour,
                       zoned.Minute,
                       zoned.Second,
                       zoned.Millisecond,
                       DateTimeKind.Unspecified));
        }
        public static Instant ToInstant(this LocalDateTime local, IDateTimeZoneProvider provider, string timeZoneId)
        {
            var timeZone = provider.GetZoneOrNull(timeZoneId);

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

            return(local.InZoneLeniently(timeZone).ToInstant());
        }
Esempio n. 4
0
 public ZoneNodeVM(string id, IDateTimeZoneProvider provider, HashSet <string> selectionStore) : this(id) {
     Data             = provider.GetZoneOrNull(id) !;
     IsSelected       = id.In(selectionStore);
     PropertyChanged += (s, e) => {
         if (e.PropertyName != nameof(IsSelected))
         {
             return;
         }
         selectionStore.AddRemove(IsSelected.Value, id);
     };
 }
Esempio n. 5
0
        public async Task <DateTimeZone> GetTimeZone(InlineQuery inlineQuery, CancellationToken cancellationToken = default)
        {
            if (inlineQuery.Location is {} userLocation)
            {
                if (TimeZoneLookup.GetTimeZone(userLocation.Latitude, userLocation.Longitude).Result is {} timeZoneId)
                {
                    if (myDateTimeZoneProvider.GetZoneOrNull(timeZoneId) is { } timeZone)
                    {
                        return(timeZone);
                    }
                }
            }

            {
                var userSettings = await myDB.Set <UserSettings>().Get(inlineQuery.From, cancellationToken);

                if (userSettings?.TimeZoneId is { } timeZoneId&& myDateTimeZoneProvider.GetZoneOrNull(timeZoneId) is { } timeZone)
                {
                    return(timeZone);
                }
            }

            return(myDefaultDateTimeZone);
        }
Esempio n. 6
0
            public NodaTimeText.ParseResult <DateTimeZone> Parse(string text)
            {
                if (string.IsNullOrWhiteSpace(text))
                {
                    return(NodaTimeText.ParseResult <DateTimeZone> .ForException(() => new ArgumentException("Time zone identifier is empty or null")));
                }

                var timeZone = _dateTimeZoneProvider.GetZoneOrNull(text);

                if (timeZone == null)
                {
                    return(NodaTimeText.ParseResult <DateTimeZone> .ForException(() => new ArgumentException("Time zone identifier unknown")));
                }

                return(NodaTimeText.ParseResult <DateTimeZone> .ForValue(timeZone));
            }
Esempio n. 7
0
        private static Func <string?, bool> IsValidTimeZoneId(IDateTimeZoneProvider provider)
        {
            return(timeZoneId =>
            {
                if (string.IsNullOrEmpty(timeZoneId))
                {
                    return false;
                }

                var zone = provider.GetZoneOrNull(timeZoneId);

                if (zone is null)
                {
                    return false;
                }

                return true;
            });
        }
Esempio n. 8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SchemaExamples"/> class.
        /// Creates example value by provided <see cref="DateTime"/> and <see cref="IDateTimeZoneProvider"/>.
        /// </summary>
        /// <param name="dateTimeZoneProvider">IDateTimeZoneProvider instance.</param>
        /// <param name="dateTimeUtc"><see cref="DateTime"/>. If not set then <see cref="DateTime.UtcNow"/> will be used.</param>
        /// <param name="dateTimeZone">Optional DateTimeZone name. If not set SystemDefault will be used.</param>
        public SchemaExamples(
            IDateTimeZoneProvider dateTimeZoneProvider,
            DateTime?dateTimeUtc = null,
            string?dateTimeZone  = null)
        {
            DateTime dateTimeUtcValue = dateTimeUtc ?? DateTime.UtcNow;

            if (dateTimeUtcValue.Kind != DateTimeKind.Utc)
            {
                throw new ArgumentException("dateTimeUtc should be UTC", nameof(dateTimeUtc));
            }

            if (dateTimeZone != null)
            {
                DateTimeZone = dateTimeZoneProvider.GetZoneOrNull(dateTimeZone) ?? dateTimeZoneProvider.GetSystemDefault();
            }
            else
            {
                DateTimeZone = dateTimeZoneProvider.GetSystemDefault();
            }

            Instant = Instant.FromDateTimeUtc(dateTimeUtcValue);

            ZonedDateTime = Instant.InZone(DateTimeZone);

            Interval = new Interval(Instant,
                                    Instant.PlusTicks(TimeSpan.TicksPerDay)
                                    .PlusTicks(TimeSpan.TicksPerHour)
                                    .PlusTicks(TimeSpan.TicksPerMinute)
                                    .PlusTicks(TimeSpan.TicksPerSecond)
                                    .PlusTicks(TimeSpan.TicksPerMillisecond));

            DateInterval = new DateInterval(ZonedDateTime.Date, ZonedDateTime.Date.PlusDays(1));

            Period = Period.Between(ZonedDateTime.LocalDateTime, Interval.End.InZone(DateTimeZone).LocalDateTime, PeriodUnits.AllUnits);

            OffsetDate = new OffsetDate(ZonedDateTime.Date, ZonedDateTime.Offset);

            OffsetTime = new OffsetTime(ZonedDateTime.TimeOfDay, ZonedDateTime.Offset);

            OffsetDateTime = Instant.WithOffset(ZonedDateTime.Offset);
        }
Esempio n. 9
0
        protected LocalTime GetCurrentZonedTime()
        {
            var          timeZoneId = GetTimeZoneId();
            DateTimeZone zone       = null;

            if (!string.IsNullOrEmpty(timeZoneId))
            {
                zone = dateTimeZoneProvider.GetZoneOrNull(timeZoneId);
            }

            if (zone == null)
            {
                timeZoneId = string.Empty;
            }

            var now = zone == null
                ? clock.GetCurrentInstant().InUtc().LocalDateTime.TimeOfDay
                : clock.GetCurrentInstant().InZone(zone).TimeOfDay;

            return(now);
        }
Esempio n. 10
0
        public ZonedDateTime Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
        {
            var str  = reader.ReadStringSegmentUnsafe();
            var i    = str.Offset;
            var date = ReadDate(str, formatterResolver, ref i);

            if (str.Array[i++] != (byte)'T')
            {
                Exceptions.ThrowInvalidDateTimeFormat(str);
            }
            var time           = ReadTime(str, formatterResolver, ref i);
            var offset         = ReadOffset(str, formatterResolver, ref i);
            var timezoneString = StringEncoding.UTF8.GetString(str.Array, i, str.Count - i + 1);
            var zone           = _dateTimeZoneProvider.GetZoneOrNull(timezoneString);

            if (zone == null)
            {
                Exceptions.ThrowInvalidTimeZone(str);
            }
            return(new ZonedDateTime(date.At(time), zone, offset));
        }
        public ZonedDateTime Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
        {
            var bsonType = context.Reader.GetCurrentBsonType();

            if (bsonType != BsonType.Document)
            {
                throw new InvalidOperationException($"{bsonType} is not a document.");
            }

            context.Reader.ReadStartDocument();
            var timezoneId = context.Reader.ReadString("timezone");
            var time       = context.Reader.ReadDateTime("datetime");
            var timezone   = _provider.GetZoneOrNull(timezoneId);

            context.Reader.ReadEndDocument();

            if (timezone == null)
            {
                throw new Exception($"TimezoneID not found {timezoneId}");
            }

            return(Instant.FromUnixTimeMilliseconds(time).InZone(timezone));
        }
Esempio n. 12
0
        public async Task <DateTimeZone> GetTimeZone(Location location, CancellationToken cancellationToken = default)
        {
            var timeZoneRequest = new TimeZoneRequest
            {
                Location  = location,
                TimeStamp = myClock.GetCurrentInstant().ToDateTimeUtc(),
                ApiKey    = myGeoCoderOptions.GoogleKey
            };
            var timeZoneResponse = await GoogleMaps.TimeZone.QueryAsync(timeZoneRequest, myTelemetryClient, cancellationToken);

            if (!timeZoneResponse.IsSuccess())
            {
                return(myClock.Zone);
            }

            if (timeZoneResponse.TimeZoneId is { } timeZoneId&&
                myDateTimeZoneProvider.GetZoneOrNull(timeZoneId) is { } dateTimeZone)
            {
                return(dateTimeZone);
            }

            return(DateTimeZone.ForOffset(Offset.FromSeconds((int)(timeZoneResponse.RawOffSet + timeZoneResponse.DstOffSet))));
        }
Esempio n. 13
0
 public override ParseResult <DateTimeZone> Parse(string value) => ParseResult <DateTimeZone> .ForValue(_dateTimeZoneProvider.GetZoneOrNull(value));
Esempio n. 14
0
 public static DateTimeZone GetTimeZone(string input) => TimezoneProvider.GetZoneOrNull(input);
        public async Task <bool?> Handle(InlineQuery data, object context = default, CancellationToken cancellationToken = default)
        {
            var results = new List <InlineQueryResult>();

            var    query     = data.Query;
            string encodedId = null;

            if (Regex.Match(query, PATTERN) is { Success : true } match)
            {
                encodedId = match.Groups["Id"].Value;
                query     = query.Remove(match.Index, match.Length);
            }
            query = query.Trim();

            var matchedZones = myDateTimeZoneProvider.Ids.Where(id =>
            {
                // check tz id
                if (id.Contains(query, StringComparison.OrdinalIgnoreCase))
                {
                    return(true);
                }

                // check Region name
                return(myTimeZoneService.TryGetRegion(id, out var region) && (
                           region.EnglishName.Contains(query, StringComparison.OrdinalIgnoreCase) ||
                           region.NativeName.Contains(query, StringComparison.OrdinalIgnoreCase)));
            }).ToList();

            InlineKeyboardMarkup replyMarkup = null;

            if (myTimeZoneNotifyService.DecodeId(encodedId, out var chatId, out var messageId))
            {
                (_, replyMarkup) = await myTimeZoneNotifyService.GetSettingsMessage(new Chat { Id = chatId, Type = ChatType.Sender }, messageId, cancellationToken);
            }
            var instant = myClock.GetCurrentInstant();

            int.TryParse(data.Offset, out var offset);
            for (var index = offset; index < matchedZones.Count && index < offset + PAGE_SIZE; index++)
            {
                var id = matchedZones[index];
                if (myDateTimeZoneProvider.GetZoneOrNull(id) is { } timeZone)
                {
                    var title   = $"{timeZone.Id} ({timeZone.GetUtcOffset(instant)})";
                    var builder = new TextBuilder()
                                  .Append($"{title}\x00A0") // trailing space is necessary to allow edit it further to the same message
                                  .NewLine();

                    string countryString = null;
                    if (myTimeZoneService.TryGetRegion(timeZone.Id, out var country))
                    {
                        countryString = $"{country.EnglishName} {country.NativeName}";
                        builder.Sanitize(countryString).NewLine();
                    }

                    results.Add(new InlineQueryResultArticle($"{PREFIX}:{encodedId}:{timeZone.Id}", title, builder.ToTextMessageContent())
                    {
                        Description = countryString,
                        ReplyMarkup = replyMarkup
                    });
                }
            }

            string nextOffset = default;

            if (results.Count == 0 && offset == 0)
            {
                results.Add(new InlineQueryResultArticle("NothingFound", "Nothing found",
                                                         new TextBuilder($"Nothing found by request ").Code(builder => builder.Sanitize(query)).ToTextMessageContent())
                {
                    Description = $"Request {query}",
                    ThumbUrl    = myUrlHelper.AssetsContent(@"static_assets/png/btn_close_normal.png").AbsoluteUri
                });
            }
            else
            {
                nextOffset = (offset + PAGE_SIZE).ToString();
            }

            await myBot.AnswerInlineQueryWithValidationAsync(data.Id, results, nextOffset : nextOffset, cacheTime : 0, isPersonal : true, cancellationToken : cancellationToken);

            return(true);
        }
Esempio n. 16
0
 private static bool IsValidTimeZone(IDateTimeZoneProvider provider, string timeZoneId)
 {
     return(provider.GetZoneOrNull(timeZoneId) != null);
 }
Esempio n. 17
0
 public DateTimeZone GetZoneOrNull(string id)
 {
     return(_provider.GetZoneOrNull(id));
 }