public void WithCalendar()
        {
            var pattern = ZonedDateTimePattern.CreateWithInvariantCulture("yyyy-MM-dd", TestProvider).WithCalendar(CalendarSystem.Coptic);
            var parsed  = pattern.Parse("0284-08-29").Value;

            Assert.AreEqual(new LocalDateTime(284, 8, 29, 0, 0, CalendarSystem.Coptic), parsed.LocalDateTime);
        }
        public void WithCulture()
        {
            var pattern = ZonedDateTimePattern.CreateWithInvariantCulture("HH:mm", null).WithCulture(Cultures.DotTimeSeparator);
            var text    = pattern.Format(Instant.FromUtc(2000, 1, 1, 19, 30).InUtc());

            Assert.AreEqual("19.30", text);
        }
 /// <summary>
 /// Creates a serializer for zoned date/times, using the given <see cref="IDateTimeZoneProvider"/>.
 /// </summary>
 /// <param name="provider">The <see cref="IDateTimeZoneProvider"/> to use when parsing.</param>
 /// <param name="pattern">The text pattern for parsing.</param>
 /// <returns>A serializer to handle <see cref="ZonedDateTime"/>.</returns>
 public static IServiceStackSerializer <ZonedDateTime> CreateZonedDateTimeSerializer(IDateTimeZoneProvider provider, string pattern = "yyyy'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFo<G> z")
 {
     return(new StandardServiceStackSerializer <ZonedDateTime>(
                ZonedDateTimePattern.CreateWithInvariantCulture(pattern, provider),
                ServiceStackFallbackDeserializers.ToZonedDateTime,
                CreateIsoValidator <ZonedDateTime>(x => x.Calendar)));
 }
        public void WithPatternText()
        {
            var pattern = ZonedDateTimePattern.CreateWithInvariantCulture("yyyy", TestProvider).WithPatternText("yyyy-MM-dd");
            var text    = pattern.Format(NodaConstants.UnixEpoch.InUtc());

            Assert.AreEqual("1970-01-01", text);
        }
Пример #5
0
        /// <summary>
        /// Returns a <see cref="ZonedDateTime"/> parsed from the given string.
        /// </summary>
        /// <param name="dateTime">The date time.</param>
        /// <param name="parsePattern">The parse pattern.</param>
        /// <returns>A <see cref="ZonedDateTime"/>.</returns>
        public static ZonedDateTime ToZonedDateTime(this string dateTime, string parsePattern)
        {
            Condition.NotEmptyOrWhiteSpace(dateTime, nameof(dateTime));
            Condition.NotEmptyOrWhiteSpace(parsePattern, nameof(parsePattern));

            return(ZonedDateTimePattern
                   .CreateWithInvariantCulture(parsePattern, DateTimeZoneProviders.Tzdb)
                   .Parse(dateTime)
                   .GetValueOrThrow());
        }
        public void WithTemplateValue()
        {
            var pattern = ZonedDateTimePattern.CreateWithInvariantCulture("yyyy-MM-dd", TestProvider)
                          .WithTemplateValue(Instant.FromUtc(1970, 1, 1, 11, 30).InZone(TestZone3));
            var parsed = pattern.Parse("2017-08-23").Value;

            Assert.AreSame(TestZone3, parsed.Zone);
            // TestZone3 is at UTC+1 in 1970, so the template value's *local* time is 12pm.
            // Even though we're parsing a date in 2017, it's the local time from the template value that's used.
            Assert.AreEqual(new LocalDateTime(2017, 8, 23, 12, 30, 0), parsed.LocalDateTime);
            Assert.AreEqual(Offset.FromHours(2), parsed.Offset);
        }
Пример #7
0
        public static DateTimeClass Parse(string text, string patternText = null)
        {
            patternText = patternText ?? ZonedDateTimePattern.GeneralFormatOnlyIso.PatternText;
            var pattern = ZonedDateTimePattern.CreateWithInvariantCulture(patternText, DateTimeHelper.Cache);

            if (!pattern.Parse(text).TryGetValue(new ZonedDateTime(), out var result))
            {
                throw new MondRuntimeException("DateTime.arse: Failed to parse input text");
            }

            return(new DateTimeClass(result));
        }
Пример #8
0
        public override async Task <string> HandleAsync(Message message, TymDbContext db)
        {
            var reply      = new StringBuilder();
            var userId     = message.From.Id;
            var fromUserId = message.ReplyToMessage?.From.Id;

            if (fromUserId == null)
            {
                var user = await db.Users
                           .Where(u => u.UserId == userId)
                           .FirstOrDefaultAsync();

                if (user == null)
                {
                    reply.AppendLine("Please set your timezone using /timezone command");
                }
                else
                {
                    var zone    = DateTimeZoneProviders.Tzdb[user.TimeZone];
                    var clock   = SystemClock.Instance.InZone(zone);
                    var now     = clock.GetCurrentZonedDateTime();
                    var pattern = ZonedDateTimePattern.CreateWithInvariantCulture("dddd MMM dd, yyyy h:mm tt z '('o<g>')'", null);
                    reply.AppendLine("Your current time is: ");
                    reply.Append(pattern.Format(now));
                }
            }
            else
            {
                var userFriend = await db.UserFriends
                                 .Include(f => f.User)
                                 .Where(f => f.UserId == fromUserId && f.FriendId == userId)
                                 .FirstOrDefaultAsync();

                if (userFriend == null)
                {
                    reply.AppendLine($"No time info found for {message.ReplyToMessage.From.Username}.");
                }
                else
                {
                    var zone    = DateTimeZoneProviders.Tzdb[userFriend.User.TimeZone];
                    var clock   = SystemClock.Instance.InZone(zone);
                    var now     = clock.GetCurrentZonedDateTime();
                    var pattern = ZonedDateTimePattern.CreateWithInvariantCulture("dddd MMM dd, yyyy h:mm tt z '('o<g>')'", null);
                    reply.AppendLine($"{message.ReplyToMessage.From.Username} current time is: ");
                    reply.Append(pattern.Format(now));
                }
            }

            return(reply.ToString());
        }
    public static void Main(string[] args)
    {
        long[] timestamps = { 1413685800L, 1413689400L, 1424568600L, 1424572200L, 1424575800L };

        var zone           = DateTimeZoneProviders.Tzdb["America/Sao_Paulo"];
        var instantPattern = InstantPattern.CreateWithInvariantCulture("dd MMM yyyy HH:mm:ss");
        var zonedPattern   = ZonedDateTimePattern.CreateWithInvariantCulture
                                 ("dd MMM yyyy HH:mm:ss o<g> (x)", null);

        foreach (long ts in timestamps)
        {
            var instant       = Instant.FromSecondsSinceUnixEpoch(ts);
            var zonedDateTime = instant.InZone(zone);

            Console.WriteLine("{0} UTC - {1}",
                              instantPattern.Format(instant),
                              zonedPattern.Format(zonedDateTime));
        }
    }
Пример #10
0
        static void Main(string[] args)
        {
            // Main variables/ values to be used
            var sourceDateTimeString  = "08/12/2018 17:37:32.525+02:00";
            var sourceDateTimeFormat  = "MM/dd/yyyy HH:mm:ss.fffzzz";
            var sourceTimeZonePattern = "Africa/Cairo";



            //var offset = DateTimeOffset.ParseExact(sourceDateTimeString, sourceDateTimeFormat, Culturei)

            //TimeZoneInfo testInfo = TimeZoneInfo.Utc;

            //var offsetFromUtc = testInfo.GetUtcOffset(Convert.ToDateTime(sourceDateTimeString));

            var convertedStringDateTime = DateTimeOffset.Parse(sourceDateTimeString, CultureInfo.GetCultureInfo("en-US")).UtcDateTime.ToString("yyyy-MM-ddTHH:mm:ss");
            //var offsetFromString = convertedDateTime.ToUniversalTime();

            var sourceDateTimeAsIsString = DateTimeOffset.Parse(sourceDateTimeString).DateTime.ToString("yyyy-MM-ddTHH:mm:ss");

            var targetTimeZone       = "UTC";
            var targetDateTimeFormat = "yyyy-MM-ddTHH:mm:ss";

            //Check if time zone provided separately and that in the DateTimeString match

            var SourceDateTimePattern = LocalDateTimePattern.CreateWithInvariantCulture(sourceDateTimeFormat);
            var SourceDateTime        = SourceDateTimePattern.Parse(sourceDateTimeAsIsString).Value;

            var TargetTimeZone = string.IsNullOrEmpty(targetTimeZone) ? sourceTimeZonePattern : targetTimeZone;
            var sourceTz       = DateTimeZoneProviders.Tzdb[sourceTimeZonePattern];
            var targetTz       = DateTimeZoneProviders.Tzdb[TargetTimeZone];

            var SourceZonedDateTime = SourceDateTime.InZoneLeniently(sourceTz);
            var TargetZonedDateTime = SourceZonedDateTime.WithZone(targetTz);


            var outPattern = ZonedDateTimePattern.CreateWithInvariantCulture(targetDateTimeFormat, DateTimeZoneProviders.Tzdb);


            var outputString = outPattern.Format(TargetZonedDateTime);

            Console.WriteLine(outPattern.Format(TargetZonedDateTime));
        }
Пример #11
0
 /// <inheritdoc />
 protected override string Serialize(ZonedDateTime runtimeValue)
 => ZonedDateTimePattern
 .CreateWithInvariantCulture(formatString, DateTimeZoneProviders.Tzdb)
 .Format(runtimeValue);
 /// <summary>
 /// Creates a converter for zoned date/times, using the given time zone provider.
 /// </summary>
 /// <param name="provider">The time zone provider to use when parsing.</param>
 /// <returns>A converter to handle <see cref="ZonedDateTime"/>.</returns>
 public static JsonConverter CreateZonedDateTimeConverter(IDateTimeZoneProvider provider) =>
 new NodaPatternConverter <ZonedDateTime>(
     ZonedDateTimePattern.CreateWithInvariantCulture("uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFFo<G> z", provider),
     CreateIsoValidator <ZonedDateTime>(x => x.Calendar));
 public NodaTimeDestructuringPolicy(IDateTimeZoneProvider provider)
 {
     _zonedDateTimePattern = ZonedDateTimePattern.CreateWithInvariantCulture("uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFFo<G> z", provider);
 }
Пример #14
0
 public ZonedDateTimeDestructuringPolicy(IDateTimeZoneProvider provider) : base(CreateIsoValidator(x => x.Calendar))
 {
     Pattern = ZonedDateTimePattern.CreateWithInvariantCulture("uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFFo<G> z", provider);
 }
Пример #15
0
 protected override bool TryDeserialize(string str, [NotNullWhen(true)] out ZonedDateTime?output)
 => ZonedDateTimePattern
 .CreateWithInvariantCulture(formatString, DateTimeZoneProviders.Tzdb)
 .TryParse(str, out output);
Пример #16
0
 private static void ReplaceConverters(IList <JsonConverter> converters, IDateTimeZoneProvider dateTimeZoneProvider)
 {
     ReplaceConverter(
         converters,
         new NewtonsoftJsonCompositeNodaPatternConverter <Instant>(
             InstantPattern.ExtendedIso,
             InstantPattern.General,
             new InstantDateTimeOffsetPattern()
             )
         );
     ReplaceConverter(
         converters,
         new NewtonsoftJsonCompositeNodaPatternConverter <LocalDate>(
             LocalDatePattern.Iso,
             LocalDatePattern.FullRoundtrip
             )
         );
     ReplaceConverter(
         converters,
         new NewtonsoftJsonCompositeNodaPatternConverter <LocalDateTime>(
             LocalDateTimePattern.ExtendedIso,
             LocalDateTimePattern.GeneralIso,
             LocalDateTimePattern.BclRoundtrip
             )
         );
     ReplaceConverter(
         converters,
         new NewtonsoftJsonCompositeNodaPatternConverter <LocalTime>(
             LocalTimePattern.ExtendedIso,
             LocalTimePattern.GeneralIso
             )
         );
     ReplaceConverter(
         converters,
         new NewtonsoftJsonCompositeNodaPatternConverter <Offset>(
             OffsetPattern.GeneralInvariant,
             OffsetPattern.GeneralInvariantWithZ
             )
         );
     ReplaceConverter(
         converters,
         new NewtonsoftJsonCompositeNodaPatternConverter <Duration>(
             DurationPattern.JsonRoundtrip,
             DurationPattern.Roundtrip
             )
         );
     ReplaceConverter(
         converters,
         new NewtonsoftJsonCompositeNodaPatternConverter <Duration>(
             DurationPattern.JsonRoundtrip,
             DurationPattern.Roundtrip
             )
         );
     ReplaceConverter(
         converters,
         new NewtonsoftJsonCompositeNodaPatternConverter <Period>(
             PeriodPattern.Roundtrip,
             PeriodPattern.NormalizingIso
             )
         );
     ReplaceConverter(
         converters,
         new NewtonsoftJsonCompositeNodaPatternConverter <OffsetDateTime>(
             OffsetDateTimePattern.GeneralIso,
             OffsetDateTimePattern.FullRoundtrip
             )
         );
     ReplaceConverter(
         converters,
         new NewtonsoftJsonCompositeNodaPatternConverter <OffsetDate>(
             OffsetDatePattern.GeneralIso,
             OffsetDatePattern.FullRoundtrip
             )
         );
     ReplaceConverter(
         converters,
         new NewtonsoftJsonCompositeNodaPatternConverter <OffsetTime>(
             OffsetTimePattern.Rfc3339,
             OffsetTimePattern.GeneralIso,
             OffsetTimePattern.ExtendedIso
             )
         );
     ReplaceConverter(
         converters,
         new NewtonsoftJsonCompositeNodaPatternConverter <ZonedDateTime>(
             ZonedDateTimePattern.CreateWithInvariantCulture("uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFFo<G> z", dateTimeZoneProvider)
             )
         );
 }
Пример #17
0
    /// <summary>
    ///     Configure System.Text.Json with defaults for launchpad
    /// </summary>
    /// <param name="options"></param>
    /// <param name="dateTimeZoneProvider"></param>
    /// <returns></returns>
    public static JsonSerializerOptions ConfigureNodaTimeForLaunchPad(this JsonSerializerOptions options, IDateTimeZoneProvider dateTimeZoneProvider)
    {
        options.ConfigureForNodaTime(dateTimeZoneProvider);
        ReplaceConverter(
            options.Converters,
            new SystemTextJsonCompositeNodaPatternConverter <Instant>(
                InstantPattern.General,
                InstantPattern.ExtendedIso,
                new InstantDateTimeOffsetPattern()
                )
            );
        ReplaceConverter(
            options.Converters,
            new SystemTextJsonCompositeNodaPatternConverter <LocalDate>(
                LocalDatePattern.Iso,
                LocalDatePattern.FullRoundtrip
                )
            );
        ReplaceConverter(
            options.Converters,
            new SystemTextJsonCompositeNodaPatternConverter <LocalDateTime>(
                LocalDateTimePattern.GeneralIso,
                LocalDateTimePattern.ExtendedIso,
                LocalDateTimePattern.BclRoundtrip
                )
            );
        ReplaceConverter(
            options.Converters,
            new SystemTextJsonCompositeNodaPatternConverter <LocalTime>(
                LocalTimePattern.ExtendedIso,
                LocalTimePattern.GeneralIso
                )
            );
        ReplaceConverter(
            options.Converters,
            new SystemTextJsonCompositeNodaPatternConverter <Offset>(
                OffsetPattern.GeneralInvariant,
                OffsetPattern.GeneralInvariantWithZ
                )
            );
        ReplaceConverter(
            options.Converters,
            new SystemTextJsonCompositeNodaPatternConverter <Duration>(
                DurationPattern.JsonRoundtrip,
                DurationPattern.Roundtrip
                )
            );
        ReplaceConverter(
            options.Converters,
            new SystemTextJsonCompositeNodaPatternConverter <Period>(
                PeriodPattern.Roundtrip,
                PeriodPattern.NormalizingIso
                )
            );
        ReplaceConverter(
            options.Converters,
            new SystemTextJsonCompositeNodaPatternConverter <OffsetDateTime>(
                OffsetDateTimePattern.GeneralIso,
                OffsetDateTimePattern.FullRoundtrip
                )
            );
        ReplaceConverter(
            options.Converters,
            new SystemTextJsonCompositeNodaPatternConverter <OffsetDate>(
                OffsetDatePattern.GeneralIso,
                OffsetDatePattern.FullRoundtrip
                )
            );
        ReplaceConverter(
            options.Converters,
            new SystemTextJsonCompositeNodaPatternConverter <OffsetTime>(
                OffsetTimePattern.Rfc3339,
                OffsetTimePattern.GeneralIso,
                OffsetTimePattern.ExtendedIso
                )
            );
        ReplaceConverter(
            options.Converters,
            new SystemTextJsonCompositeNodaPatternConverter <ZonedDateTime>(
                ZonedDateTimePattern.CreateWithInvariantCulture("uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFFo<G> z", dateTimeZoneProvider)
                )
            );

        return(options);
    }
Пример #18
0
 /// <inheritdoc />
 protected override bool TryDeserialize(
     string resultValue,
     [NotNullWhen(true)] out ZonedDateTime?runtimeValue)
 => ZonedDateTimePattern
 .CreateWithInvariantCulture(formatString, DateTimeZoneProviders.Tzdb)
 .TryParse(resultValue, out runtimeValue);
Пример #19
0
        public override async Task <string> HandleAsync(Message message, TymDbContext db)
        {
            var textMessage = message.Text.Trim();
            var reply       = new StringBuilder();
            var userId      = message.From.Id;
            var fromUserId  = message.ReplyToMessage?.From.Id;
            var inputZone   = textMessage
                              .Replace($"/{BotCommands.Timezone}@{BotService.Bot.Username}", "")
                              .Replace($"/{BotCommands.Timezone}", "")
                              .Trim()
                              .ToLower();

            var timezone = DateTimeZoneProviders.Tzdb.Ids.SingleOrDefault(id => id.ToLower() == inputZone);

            if (timezone == null)
            {
                var timezones = DateTimeZoneProviders.Tzdb.Ids
                                .Where(id => id.ToLower().Contains(inputZone))
                                .Take(10);

                if (timezones.Count() == 0)
                {
                    timezones = DateTimeZoneProviders.Tzdb.Ids.Take(10);
                }

                reply.AppendLine("Sample usage: /timezone Asia/Tokyo");
                reply.AppendLine("\nAre you looking for these timezones?\n");
                foreach (var z in timezones)
                {
                    reply.AppendLine(z);
                }
            }
            else
            {
                var user = await db.Users
                           .Where(f => f.UserId == userId)
                           .FirstOrDefaultAsync();

                if (user == null)
                {
                    user = new Models.User()
                    {
                        UserId   = userId,
                        TimeZone = timezone,
                        Name     = message.From.FirstName,
                    };
                    db.Users.Add(user);
                    await db.SaveChangesAsync();
                }
                else
                {
                    user.TimeZone = timezone;
                    user.Name     = message.From.FirstName;
                    await db.SaveChangesAsync();
                }

                var zone    = DateTimeZoneProviders.Tzdb[timezone];
                var clock   = SystemClock.Instance.InZone(zone);
                var now     = clock.GetCurrentZonedDateTime();
                var pattern = ZonedDateTimePattern.CreateWithInvariantCulture("dddd MMM dd, yyyy h:mm tt z '('o<g>')'", null);
                reply.AppendLine("Your current time is: ");
                reply.Append(pattern.Format(now));
            }

            return(reply.ToString());
        }