/// <summary> /// Convert a given datetime from a timezone to another timezone /// </summary> /// <param name="datetime"></param> /// <param name="from"></param> /// <param name="to"></param> /// <returns></returns> public static ZonedDateTime ConvertDateTimeToDifferentTimeZone(DateTime datetime, DateTimeZone from, DateTimeZone to) { var fromLocal = LocalDateTime.FromDateTime(datetime); ZonedDateTime fromDatetime = from.AtStrictly(fromLocal); return(fromDatetime.WithZone(to)); }
private static ZonedDateTime GetJobsZonedDateTime(RecurringJobDto rJobDto, DateTimeZone hostDTZ) { LocalDateTime ldt = LocalDateTime.FromDateTime(rJobDto.NextExecution !.Value); ZonedDateTime zdt = ldt.InUtc(); zdt = zdt.WithZone(hostDTZ); return(zdt); }
public static ZonedDateTime ToTimeZone(DateTime datetime, string fromTzId, string toTzId, TimeSpan offset) { var oldZone = GetTimeZone(fromTzId); var oldZonedTime = new ZonedDateTime(LocalDateTime.FromDateTime(datetime), oldZone, Offset.FromHoursAndMinutes(offset.Hours, offset.Minutes)); var newZone = GetTimeZone(toTzId); var convertedTime = oldZonedTime.WithZone(newZone); return(convertedTime); }
public void WithZone() { DateTimeZone london = DateTimeZone.ForId("Europe/London"); DateTimeZone hawaii = DateTimeZone.ForId("Pacific/Honolulu"); ZonedDateTime uk = new ZonedDateTime(SystemClock.Instance.Now, london); Console.WriteLine(uk); Console.WriteLine(uk.WithZone(hawaii)); }
/// <summary> /// Convert Eastern Time into Mountain Time /// </summary> /// <param name="dateToTest">Eastern Time</param> /// <param name="tzMountain">Mountain TimeZone</param> private static void ShowConversion(ZonedDateTime dateToTest, DateTimeZone tzMountain) { ZonedDateTime convertedTime = dateToTest.WithZone(tzMountain); // for some reason the 'x' format pattern is not working, so they are ginned up as constants // 'x' is printing the full timezone name e.g. "Eastern Standard Time" Console.WriteLine("{0:MM/dd/yyyy HH:mm x} {1} => {2:MM/dd/yyyy HH:mm x} {3}", dateToTest, IsDaylightSavingsTime(dateToTest) ? "EDT" : "EST", convertedTime, IsDaylightSavingsTime(convertedTime) ? "MDT" : "MST"); }
/// <summary> /// Round down a given zoned datetime to the nearest time of emission. /// </summary> /// <param name="zonedBarTime">The zoned bar datetime to be rounded down.</param> /// <returns>The rounded down and zoned bar time (TZ: <see cref="CloseTimeZone"/>).</returns> protected ZonedDateTime RoundDownToLastEmitTime(ZonedDateTime zonedBarTime) { // Convert time given to the same timezone as the close specified if it isn't already var zonedConvertedBarTimeDT = zonedBarTime.WithZone(CloseTimeZone); // Get timezoned close (now that we have a date) var zonedDailyCloseDT = CloseTimeZone.AtLeniently(zonedConvertedBarTimeDT.Date + DailyCloseTime); // Return the last close, zoned into the close timezone return(zonedConvertedBarTimeDT.TimeOfDay >= zonedDailyCloseDT.TimeOfDay ? zonedDailyCloseDT : zonedDailyCloseDT - Duration.FromStandardDays(1)); }
public void CompareTo_DifferentZones_OnlyInstantMatters() { var otherZone = new FixedDateTimeZone(Offset.FromHours(-20)); ZonedDateTime value1 = SampleZone.AtStrictly(new LocalDateTime(2011, 1, 2, 10, 30)); // Earlier local time, but later instant ZonedDateTime value2 = otherZone.AtStrictly(new LocalDateTime(2011, 1, 2, 5, 30)); ZonedDateTime value3 = value1.WithZone(otherZone); Assert.That(value1.CompareTo(value2), Is.LessThan(0)); Assert.That(value2.CompareTo(value1), Is.GreaterThan(0)); Assert.That(value1.CompareTo(value3), Is.EqualTo(0)); }
public void WithZone() { Instant instant = Instant.FromUtc(2012, 2, 4, 12, 35); ZonedDateTime zoned = new ZonedDateTime(instant, SampleZone); Assert.AreEqual(new LocalDateTime(2012, 2, 4, 16, 35, 0), zoned.LocalDateTime); // Will be UTC-8 for our instant. DateTimeZone newZone = new SingleTransitionDateTimeZone(Instant.FromUtc(2000, 1, 1, 0, 0), -7, -8); ZonedDateTime converted = zoned.WithZone(newZone); Assert.AreEqual(new LocalDateTime(2012, 2, 4, 4, 35, 0), converted.LocalDateTime); Assert.AreEqual(converted.ToInstant(), instant); }
public void Can_Query_By_Equals_Using_A_UtcTime_OffsetDateTime_Stored_As_DateTimeOffset() { var timeZoneUnitedKingdom = DateTimeZoneProviders.Tzdb.GetZoneOrNull("Europe/London"); LocalDateTime localTimeInUnitedKingom = new LocalDateTime(2016, 06, 01, 10, 40); ZonedDateTime zonedStartDateTime = localTimeInUnitedKingom.InZoneStrictly(timeZoneUnitedKingdom); ZonedDateTime zonedFinishDateTime = zonedStartDateTime.Plus(Duration.FromMinutes(60)); ZonedDateTime matchingUtcZonedDateTime = zonedStartDateTime.WithZone(DateTimeZone.Utc); var offsetStartTime = new OffsetDateTime(zonedStartDateTime.LocalDateTime, zonedStartDateTime.Offset); var offsetFinishTime = new OffsetDateTime(zonedFinishDateTime.LocalDateTime, zonedFinishDateTime.Offset); var offsetStartTimeUtc = matchingUtcZonedDateTime.ToOffsetDateTime(); var testEvent = new OffsetDateTimeTestEntity { Description = "Can_Query_By_Equals_Using_A_UtcTime_OffsetDateTime_Stored_As_DateTimeOffset", SystemDateTimeOffset = DateTimeOffset.Now, StartOffsetDateTime = offsetStartTime, FinishOffsetDateTime = offsetFinishTime }; using (ISession session = SessionFactory.OpenSession()) using (ITransaction transaction = session.BeginTransaction()) { session.Save(testEvent); transaction.Commit(); } // Even though two OffsetDateTimes may refer to the same instant... Assert.That(offsetStartTime.ToInstant(), Is.EqualTo(offsetStartTimeUtc.ToInstant())); // They are not considered equal by NodaTime unless the LocalDateTime and Offset parts are both equal. // (There is nothing wrong with this, it is perfectly valid logic for comparing two OffsetDateTimes.) Assert.That(offsetStartTime, Is.Not.EqualTo(offsetStartTimeUtc)); // However we are storing OffsetDateTimes as DateTimeOffsets in the sql server. // So when using Linq and sending the expression to the sql server, // the sql server will convert all DateTimeOffsets to utc time before comparing them. // Therefore the same two OffsetDateTimes that are not equal as shown above are seen as being equal by sql. using (ISession session = SessionFactory.OpenSession()) using (ITransaction transaction = session.BeginTransaction()) { var query = session.Query <OffsetDateTimeTestEntity>().Where(x => x.StartOffsetDateTime == offsetStartTimeUtc); var retrievedEvent = query.SingleOrDefault(); transaction.Commit(); Assert.That(testEvent, Is.Not.Null); Assert.That(testEvent, Is.EqualTo(retrievedEvent)); } }
/// <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); }
// It's probably most convenient to express the event time with the time zone // in which it occurs. You could easily change this though. public EventCountdown(ZonedDateTime zonedEventTime, IClock clock) { this.eventTimeUtc = zonedEventTime.WithZone(DateTimeZone.Utc).LocalDateTime; this.clock = clock; }
private async Task SendAdjustedDate(DiscordClient c, MessageReactionAddEventArgs e) { if (e.User.IsBot) { return; } if (e.Channel.IsPrivate) { return; } DiscordChannel channel = await c.GetChannelAsync(e.Channel.Id); _ = Task.Run(async() => { if (e.Emoji.Equals(this.ClockEmoji)) { try { DiscordMember reactor = (DiscordMember)e.User; DiscordMessage msg = await channel.GetMessageAsync(e.Message.Id); DbResult <UserTimeZone> opTimeZoneResult = await this.Mediator.Send(new UserTimeZones.GetUsersTimeZone(msg.Author)); if (!opTimeZoneResult.TryGetValue(out UserTimeZone? opTimeZoneEntity)) { await reactor.SendMessageAsync("The original poster has not set up a time zone yet."); return; } string opTimeZoneId = opTimeZoneEntity.TimeZoneId; DateTimeZone?opTimeZone = this.TimeZoneProvider.GetZoneOrNull(opTimeZoneId); DbResult <UserTimeZone> reactorTimeZoneResult = await this.Mediator.Send(new UserTimeZones.GetUsersTimeZone(msg.Author)); if (!reactorTimeZoneResult.TryGetValue(out UserTimeZone? reactorTimeZoneEntity)) { await reactor.SendMessageAsync("You have not set up a time zone yet. Use `time init` to set up your time zone."); return; } string reactorTimeZoneId = reactorTimeZoneEntity.TimeZoneId; DateTimeZone?reactorTimeZone = this.TimeZoneProvider.GetZoneOrNull(reactorTimeZoneId); if (opTimeZone == null || reactorTimeZone == null) { await reactor.SendMessageAsync("There was a problem, please reach out to your bot developer."); return; } ZonedDateTime zonedMessageDateTime = ZonedDateTime.FromDateTimeOffset(msg.CreationTimestamp); DateTime opRefTime = zonedMessageDateTime.WithZone(opTimeZone).ToDateTimeOffset().DateTime; IEnumerable <DateTimeV2ModelResult> parserList = Recognizers.RecognizeDateTime(e.Message.Content, opRefTime, DateTimeV2Type.Time, DateTimeV2Type.DateTime); if (!parserList.Any()) { await reactor.SendMessageAsync("This message does not have a recognizable time in it."); return; } DiscordEmbedBuilder reactorTimeEmbed = new DiscordEmbedBuilder().WithTitle("You requested a timezone conversion"); IEnumerable <(string, DateTimeV2Value)> results = parserList.SelectMany(x => x.Values.Select(y => (x.Text, y))); foreach ((string parsedText, DateTimeV2Value result) in results) { string outputString; if (result.Type is DateTimeV2Type.Time) { LocalTime localParsedTime = (LocalTime)result.Value; LocalDateTime localParsedDateTime = localParsedTime.On(zonedMessageDateTime.LocalDateTime.Date); ZonedDateTime zonedOpDateTime = localParsedDateTime.InZoneStrictly(opTimeZone); ZonedDateTime zonedReactorDateTime = zonedOpDateTime.WithZone(reactorTimeZone); outputString = zonedReactorDateTime.LocalDateTime.TimeOfDay.ToString("t", null); } else { LocalDateTime localParsedDateTime = (LocalDateTime)result.Value; ZonedDateTime zonedOpDateTime = localParsedDateTime.InZoneStrictly(opTimeZone); ZonedDateTime zonedReactorDateTime = zonedOpDateTime.WithZone(reactorTimeZone); outputString = zonedReactorDateTime.LocalDateTime.ToString("g", null); } reactorTimeEmbed .AddField("Poster's Time", $"\"{parsedText}\"") .AddField("Your time", $"{outputString}"); } await reactor.SendMessageAsync(embed: reactorTimeEmbed); } catch (Exception exception) { this.Logger.Log(LogLevel.Error, exception, "Error in sending reactor the DM"); } } }); }
private async Task SendAdjustedDate(DiscordClient c, MessageReactionAddEventArgs e) { if (e.User.IsBot) { return; } DiscordChannel channel = await c.GetChannelAsync(e.Channel.Id); _ = Task.Run(async() => { if (e.Emoji.Equals(this.clockEmoji)) { try { using IBotAccessProvider database = this.providerBuilder.Build(); DiscordMember reactor = (DiscordMember)e.User; DiscordMessage msg = await channel.GetMessageAsync(e.Message.Id); IEnumerable <DateTimeV2ModelResult> parserList = DateTimeRecognizer.RecognizeDateTime(msg.Content, culture: Culture.English) .Select(x => x.ToDateTimeV2ModelResult()).Where(x => x.TypeName is DateTimeV2Type.Time or DateTimeV2Type.DateTime); if (!parserList.Any()) { await reactor.SendMessageAsync("Hey, you're stupid, stop trying to react to messages that don't have times in them."); return; } DiscordEmbedBuilder reactorTimeEmbed = new DiscordEmbedBuilder().WithTitle("You requested a timezone conversion"); string opTimeZoneId = database.GetUsersTimeZone(msg.Author.Id)?.TimeZoneId; string reactorTimeZoneId = database.GetUsersTimeZone(e.User.Id)?.TimeZoneId; if (opTimeZoneId is null) { await reactor.SendMessageAsync("The original poster has not set up a time zone yet."); return; } if (reactorTimeZoneId is null) { await channel.SendMessageAsync("You have not set up a time zone yet. Use `time init` to set up your time zone."); return; } DateTimeZone opTimeZone = this.timeZoneProvider.GetZoneOrNull(opTimeZoneId); DateTimeZone reactorTimeZone = this.timeZoneProvider.GetZoneOrNull(reactorTimeZoneId); if (opTimeZone == null || reactorTimeZone == null) { await reactor.SendMessageAsync("There was a problem, please reach out to your bot developer."); return; } IEnumerable <(string, DateTimeV2Value)> results = parserList.SelectMany(x => x.Values.Select(y => (x.Text, y))); foreach ((string parsedText, DateTimeV2Value result) in results) { string outputString; if (result.Type is DateTimeV2Type.Time) { DateTimeOffset messageDateTime = msg.Timestamp; ZonedDateTime zonedMessageDateTime = ZonedDateTime.FromDateTimeOffset(messageDateTime); LocalTime localParsedTime = (LocalTime)result.Value; LocalDateTime localParsedDateTime = localParsedTime.On(zonedMessageDateTime.LocalDateTime.Date); ZonedDateTime zonedOpDateTime = localParsedDateTime.InZoneStrictly(opTimeZone); ZonedDateTime zonedReactorDateTime = zonedOpDateTime.WithZone(reactorTimeZone); outputString = zonedReactorDateTime.LocalDateTime.TimeOfDay.ToString("t", null); } else { LocalDateTime localParsedDateTime = (LocalDateTime)result.Value; ZonedDateTime zonedOpDateTime = localParsedDateTime.InZoneStrictly(opTimeZone); ZonedDateTime zonedReactorDateTime = zonedOpDateTime.WithZone(reactorTimeZone); outputString = zonedReactorDateTime.LocalDateTime.ToString("g", null); } reactorTimeEmbed .AddField("Poster's Time", $"\"{parsedText}\"") .AddField("Your time", $"{outputString}"); } await reactor.SendMessageAsync(embed: reactorTimeEmbed); } catch (Exception exception) { this.logger.Log(LogLevel.Error, exception, "Error in sending reactor the DM"); } } }); }
public ZonedDateTimeRange WithZone(DateTimeZone dateTimeZone) { return(new ZonedDateTimeRange(_start.WithZone(dateTimeZone), _end.WithZone(dateTimeZone))); }