Exemple #1
0
        public static string GetDisplayString(this Instant self)
        {
            DateTimeZone  zone    = DateTimeZoneProviders.Tzdb.GetSystemDefault();
            ZonedDateTime zdt     = self.InZone(zone);
            StringBuilder builder = new StringBuilder();

            builder.Append(zdt.ToString(@"hh:mm ", CultureInfo.InvariantCulture));
            builder.Append(zdt.ToString(@"tt", CultureInfo.InvariantCulture).ToLower());
            builder.Append(zdt.ToString(@" dd/MM/yyyy", CultureInfo.InvariantCulture).ToLower());
            return(builder.ToString());
        }
Exemple #2
0
        public void ShouldGenerateCorrectString(int year, int month, int day, int hour, int minute, int second, int nanosecond, string zoneId, string expected)
        {
            var cypherDateTime    = new ZonedDateTime(year, month, day, hour, minute, second, nanosecond, Zone.Of(zoneId));
            var cypherDateTimeStr = cypherDateTime.ToString();

            cypherDateTimeStr.Should().Be(expected);
        }
Exemple #3
0
        private static Stream GetFrogImage(ZonedDateTime zonedDateTime)
        {
            var img       = System.Drawing.Image.FromFile("Files/frog.jpg");
            var gr        = Graphics.FromImage(img);
            var font      = new Font("Times New Roman", 20, FontStyle.Regular);
            var strFormat = new StringFormat()
            {
                Alignment = StringAlignment.Center
            };

            gr.DrawString("Gentlemen, it is with great pleasure to inform you that",
                          font,
                          Brushes.White,
                          new RectangleF(20, 20, img.Width - 40, img.Height - 20),
                          strFormat);
            gr.DrawString($"today is {zonedDateTime.ToString("dddd, MMMM d", null)}",
                          font,
                          Brushes.White,
                          new RectangleF(20, 450, img.Width - 40, img.Height - 450),
                          strFormat);
            var stream = new MemoryStream();

            img.Save(stream, img.RawFormat);
            stream.Position = 0;
            return(stream);
        }
        public void ZonedDateTime_ToString()
        {
            var           local = new LocalDateTime(2013, 7, 23, 13, 05, 20);
            ZonedDateTime zoned = local.InZoneStrictly(SampleZone);

            Assert.AreEqual("2013-07-23T13:05:20 Single (+04)", zoned.ToString());
        }
        public void ZonedDateTime_ToString_WithFormat()
        {
            var           local = new LocalDateTime(2013, 7, 23, 13, 05, 20);
            ZonedDateTime zoned = local.InZoneStrictly(SampleZone);

            Assert.AreEqual("2013/07/23 13:05:20 Single", zoned.ToString("yyyy/MM/dd HH:mm:ss z", CultureInfo.InvariantCulture));
        }
        public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            Instant instant;

            switch (value)
            {
            case Instant instant1:
                instant = instant1;
                break;

            case string s:
                var parseResult = InstantPattern.ExtendedIso.Parse(s);
                if (!parseResult.Success)
                {
                    return(UnsetValue);
                }
                instant = parseResult.Value;
                break;

            default:
                return(UnsetValue);
            }

            var zone          = parameter as DateTimeZone ?? Tzdb.GetSystemDefault();
            var zonedDateTime = new ZonedDateTime(instant, zone);

            return($"{instant.ToString("g", culture)}\n{zonedDateTime.ToString("F", culture)}");
        }
Exemple #7
0
        public static string GetZonedDate(DateTime dt, string format)
        {
            DateTimeZone tz  = DateTimeZoneProviders.Tzdb["Europe/Prague"]; // Get the system's time zone
            var          zdt = new ZonedDateTime(Instant.FromDateTimeUtc(DateTime.SpecifyKind(dt, DateTimeKind.Utc)), tz);

            return(zdt.ToString(format, CultureInfo.InvariantCulture));
        }
Exemple #8
0
 public IEnumerable <string> Format(LogLevel level, string message)
 {
     using (var reader =
                new StringReader(message))
     {
         string line;
         while ((line = reader.ReadLine()) != null)
         {
             ZonedDateTime now = _Clock.GetCurrentInstant().InZone(_SystemTimeZone);
             yield return($"{now.ToString("yyyy-MM-dd HH:mm:ss.fff", _InvariantCulture)} {_LogLevelNames[level],-5}: {line}");
         }
     }
 }
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            Preferences = parameter as IUserPreferences;

            if (Preferences == null)
            {
                Log.Error("Parameter must be an IUserPreferences");
                throw new ArgumentException("Parameter must be an instance of IUserPreferences", nameof(parameter));
            }

            var message = value as ILogEntry;

            if (message == null)
            {
                Log.Warn("Not supplied an ILogEntry as the value parameter");
                return(string.Empty);
            }

            object displayDateTime = null;

            if (Preferences.UseArrivalDateTime)
            {
                message.MetaData.TryGetValue("ReceivedTime", out displayDateTime);
            }

            // Fallback if message does not contain meta-data.
            var dt    = (DateTime)(displayDateTime ?? message.DateTime);
            var isUtc = dt.Kind == DateTimeKind.Utc;

            if (isUtc && Preferences.ConvertUtcTimesToLocalTimeZone)
            {
                var defaultTimeZone = DateTimeZoneProviders.Tzdb.GetSystemDefault();
                var global          = new ZonedDateTime(Instant.FromDateTimeUtc(dt), defaultTimeZone);
                return
                    (global.ToString(
                         GetDateDisplayFormat(Preferences.SelectedTimeFormatOption, Preferences.TimeFormatOptions, true),
                         CultureInfo.CurrentCulture));
            }

            var local = LocalDateTime.FromDateTime(dt);
            var time  =
                local.ToString(
                    GetDateDisplayFormat(Preferences.SelectedTimeFormatOption, Preferences.TimeFormatOptions, false),
                    CultureInfo.CurrentCulture);

            return(isUtc ? time + " [UTC]" : time);
        }
Exemple #10
0
        /// <summary>
        /// Generate the embed with the randomly selected movies and add emojis to allow for voting
        /// </summary>
        /// <param name="movieNightId">ID for the movie night in the data store</param>
        /// <exception cref="ArgumentException">Thrown when an unknown movie night ID is provided</exception>
        public async Task StartVoting(int movieNightId)
        {
            GuildMovieNight movieNight = await GetGuildMovieNightAsync(movieNightId);

            (DiscordClient client, DiscordGuild guild, DiscordChannel channel) = await this.GetCommonDiscordObjects(movieNight);

            DbResult <IEnumerable <GuildMovieSuggestion> > randomSuggestionsResult = await this
                                                                                     .mediator.Send(new GuildMovieSuggestions.GetRandomGuildMovieSuggestions(guild, movieNight.NumberOfSuggestions, movieNight.MaximumRating));

            if (!randomSuggestionsResult.TryGetValue(out IEnumerable <GuildMovieSuggestion>?randomSuggestions))
            {
                throw new Exception("Something went wrong with getting the random suggestions.");
            }

            string          description = AddMovieSuggestionsAndGenerateDescription(client, movieNight, randomSuggestions);
            RecurringJobDto rJobDto     = GetMovieNightStartRecurringJobInfo(movieNight);

            DateTimeZone hostDTZ = await GetUserDateTimeZone(movieNight.HostId);

            ZonedDateTime zdt = GetJobsZonedDateTime(rJobDto, hostDTZ);

            DiscordEmbed eBuilder = new DiscordEmbedBuilder()
                                    .WithTitle($"Time to vote for a movie!")
                                    .WithDescription(description)
                                    .AddField("Date and Time of Movie", zdt.ToString("MM/dd/yyyy hh:mm x", null), true)
                                    .AddField("Maximum Parental Rating", movieNight.MaximumRating.ToQueryValue(), true);

            DiscordMessageBuilder mBuilder = new DiscordMessageBuilder()
                                             .WithContent("@everyone")
                                             .WithEmbed(eBuilder);

            DiscordMessage votingMessage = await channel.SendMessageAsync(mBuilder);

            movieNight.VotingMessageId = votingMessage.Id;

            await this.mediator.Send(new GuildMovieNights.Update(movieNight));

            foreach (DiscordEmoji emoji in GetNumberEmojis(client).Take(randomSuggestions.Count()))
            {
                await votingMessage.CreateReactionAsync(emoji);
            }
        }
Exemple #11
0
        private void cmbTimeZone_SelectedIndexChanged(object sender, EventArgs e)
        {
            timeZone = DateTimeZoneProviders.Tzdb[cmbTimeZone.SelectedItem.ToString()];
            updateFormattedDatetime();
            //Convert from a DateTime selection (assuming it is local time) back to Instant for db storage
            //Create a LocalTime using DateTime.Now
            LocalDateTime localDateTime = LocalDateTime.FromDateTime(DateTime.Now);
            ZonedDateTime zonedDateTime = localDateTime.InZoneLeniently(timeZone);
            Instant       instant       = zonedDateTime.ToInstant();

            txtTimeZoneInfo.Clear();
            txtTimeZoneInfo.Text  = "DateTime.Now: " + DateTime.Now.ToString();
            txtTimeZoneInfo.Text += Environment.NewLine;
            txtTimeZoneInfo.Text += Environment.NewLine + "Local Date Time: " + localDateTime.ToString();
            txtTimeZoneInfo.Text += Environment.NewLine + " - LocalDateTime localDateTime = LocalDateTime.FromDateTime(DateTime.Now);";
            txtTimeZoneInfo.Text += Environment.NewLine;
            txtTimeZoneInfo.Text += Environment.NewLine + "Zoned Date Time: " + zonedDateTime.ToString();
            txtTimeZoneInfo.Text += Environment.NewLine + " - ZonedDateTime zonedDateTime = localDateTime.InZoneLeniently(timeZone);";
            txtTimeZoneInfo.Text += Environment.NewLine;
            txtTimeZoneInfo.Text += Environment.NewLine + "Instant: " + instant.ToString();
            txtTimeZoneInfo.Text += Environment.NewLine + " - Instant instant = zonedDateTime.ToInstant();";
        }
 public override string ToString() => _value.ToString();
Exemple #13
0
        /// <summary>
        /// Determine the number of votes that each movie got and then select the highest ranked movie.
        /// If there is a tie on more than one of the movies, message the movie night creator with an
        /// embed where they will break the tie.
        /// </summary>
        /// <param name="movieNightId">ID for the movie night in the data store</param>
        public async Task CalculateVotes(int movieNightId)
        {
            GuildMovieNight movieNight = await GetGuildMovieNightAsync(movieNightId);

            (DiscordClient client, DiscordGuild guild, DiscordChannel channel) = await this.GetCommonDiscordObjects(movieNight);

            DiscordMessage votingMessage = await channel.GetMessageAsync(movieNight.VotingMessageId ?? throw new Exception("Somehow, some way, the voting message id was null... something done f$*@ed up."));

            Dictionary <string, DiscordReaction> mostReactedReactions = GetMostReactedReactons(votingMessage);

            DiscordMember host = await guild.GetMemberAsync(movieNight.HostId);

            GuildMovieSuggestion winningSuggestion = await GetWinningSuggestion(client, guild, host, movieNight, mostReactedReactions);

            movieNight.WinningMovieImdbId = winningSuggestion.ImdbId;
            DbResult movieNightUpdateResult = await this.mediator.Send(new GuildMovieNights.Update(movieNight));

            if (!movieNightUpdateResult.Success)
            {
                throw new Exception("An error occurred in updating the movie night with the winning suggestion");
            }

            RecurringJobDto rJobDto = GetMovieNightStartRecurringJobInfo(movieNight);

            LocalDateTime ldt     = LocalDateTime.FromDateTime(rJobDto.NextExecution !.Value);
            DateTimeZone  hostDTZ = await GetUserDateTimeZone(movieNight.HostId);

            ZonedDateTime zdt = ldt.InUtc();

            zdt = zdt.WithZone(hostDTZ);

            OmdbMovie movieInfo = await this.omdbClient.GetByImdbIdAsync(winningSuggestion.ImdbId, omdbPlotOption : OmdbPlotOption.SHORT);

            DiscordEmbedBuilder announceWinnerEmbed = movieInfo.ToDiscordEmbedBuilder(true)
                                                      .WithAuthor(host.DisplayName, iconUrl: host.AvatarUrl);
            DiscordMessageBuilder announceWinnerMessage = new DiscordMessageBuilder()
                                                          .WithContent($"@everyone, here's what {host.Mention} is showing {zdt.ToString("MM/dd/yyyy hh:mm x", null)}")
                                                          .WithEmbed(announceWinnerEmbed.Build());

            await channel.SendMessageAsync(announceWinnerMessage);
        }
 public override string ToString()
 {
     return(Time.ToString("yyyy/MM/dd HH:mm:ss", CultureInfo.InvariantCulture));
 }
Exemple #15
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void writeDateTime(java.time.ZonedDateTime zonedDateTime) throws RuntimeException
        public override void WriteDateTime(ZonedDateTime zonedDateTime)
        {
            Append("{datetime: ");
            Append(Quote(zonedDateTime.ToString()));
            Append("}");
        }
Exemple #16
0
        /// <summary>
        /// Returns a string formatted to the millisecond (ISO-8601) from the given
        /// <see cref="ZonedDateTime"/>.
        /// </summary>
        /// <param name="time">The time.</param>
        /// <returns>A <see cref="string"/>.</returns>
        public static string ToIso8601String(this ZonedDateTime time)
        {
            Debug.NotDefault(time, nameof(time));

            return(time.ToString(Iso8601DateTimeParsePattern, CultureInfo.InvariantCulture.DateTimeFormat) + "Z");
        }
Exemple #17
0
 /// <summary>
 /// Returns the date time parsed from the given string.
 /// </summary>
 /// <param name="expireTime">The expire time.</param>
 /// <returns>The converted <see cref="ZonedDateTime"/>.</returns>
 public static string ToExpireTimeFormat(ZonedDateTime expireTime)
 {
     // ReSharper disable once StringLiteralTypo (correct format)
     return(expireTime.ToString("MMddyyyyHHmmss", CultureInfo.InvariantCulture.DateTimeFormat));
 }
Exemple #18
0
 public static string ToPrettyTime(this ZonedDateTime dateTime)
 {
     return(dateTime.ToString("HH:mm", CultureInfo.InvariantCulture));
 }
Exemple #19
0
 public override string ToString()
 {
     return(SliceStart.ToString("F", null));
 }