/// <summary> /// Converts the UTC time to local time. /// </summary> /// <param name="utcTime">The UTC time.</param> /// <param name="tzID">The tz identifier. It is the same as IANA TZdb in database</param> /// <returns></returns> public static DateTime ConvertUnixEpochToLocalTime(int secondsSinceUnixEpoch, string tzID) { Instant time = Instant.FromSecondsSinceUnixEpoch(secondsSinceUnixEpoch); var dateTimeZone = GetTimeZoneProvider()[tzID]; ZonedDateTime zonedDateTime = time.InZone(dateTimeZone); return(zonedDateTime.ToDateTimeUnspecified()); }
public static int GetTimezoneOffsetFromLocationAndDateInSeconds(long timestamp, int latitude, int longitude) { var timezone = TimeZoneLookup.GetTimeZone(FixedPointCoordConversion.ToDouble(latitude), FixedPointCoordConversion.ToDouble(longitude)); Instant instant = new Instant(timestamp * 1000); ZonedDateTime zdt = instant.InZone(DateTimeZoneProviders.Tzdb[timezone.Result]); return(zdt.Offset.Milliseconds / 1000); }
static void Main() { Instant instant = Instant.FromUnixTimeSeconds(1535308200); DateTimeZone zone = DateTimeZoneProviders.Tzdb["Europe/Paris"]; ZonedDateTime zoned = instant.InZone(zone); Console.WriteLine(zoned); }
private static string GetTimeDisplay(Instant instant, DateTimeZone timeZone, bool isTwentyFourTime = false) { ZonedDateTime zonedDateTime = instant.InZone(timeZone); string timeFormatString = isTwentyFourTime ? "HH:mm" : "h:mm tt"; string timeOfDay = zonedDateTime.TimeOfDay.ToString(timeFormatString, CultureInfo.InvariantCulture); return($"{zonedDateTime.DayOfWeek}s at {timeOfDay}"); }
public Instant GetNextRunTime(Instant currentInstant) => currentInstant .InZone(DateCalculator.LondonTimeZone) .Date .Next(IsoDayOfWeek.Wednesday) .AtMidnight() .InZoneStrictly(DateCalculator.LondonTimeZone) .ToInstant();
public static string ToString(this Instant instant, string cultureTab, DateTimeZone zone, bool withoutDaylightSaving = false, MxCultureInfo.FormatType formatType = MxCultureInfo.FormatType.DateTime, bool longFormat = false) { var rc = "[error]"; if ((zone != null) && (String.IsNullOrEmpty(cultureTab) == false)) { try { var culture = MxCultureInfo.Instance.GetCultureInfo(cultureTab); if (culture != null) { var local = instant.InZone(zone).LocalDateTime; if (withoutDaylightSaving && zone.IsDaylightSavingsTime(instant)) { local = local.Minus(Period.FromSeconds(zone.GetZoneInterval(instant).Savings.Seconds)); } // ReSharper disable once ReturnValueOfPureMethodIsNotUsed zone.AtStrictly(local); //throws exception if ambiguous or invalid due to daylight saving transition //In all formats except Date the setting of longFormat (capital letter) causes display of hours, minutes and seconds in 24 hour clock //FormatType.Date: en-GB: D=Sunday, 29 March 2020 d=29-03-2020 //FormatType.Time: en-GB: T=00:59:59 t=12:59 AM //FormatType.DateTime: en-GB: G=29-03-2020 00:59:59 g=29-03-2020 12:59 AM //FormatType.Verbose: en-GB: F=Sunday, 29 March 2020 00:59:59 f=Sunday, 29 March 2020 12:59 AM //FormatType.Machine: *: r=2020-03-29T00:59:59.000000000(ISO) s=2020-03-29T00 59:59 if (formatType == MxCultureInfo.FormatType.Date) { rc = local.Date.ToString(MxCultureInfo.GetFormatSpecifier(formatType, longFormat), culture); } else if (formatType == MxCultureInfo.FormatType.Time) { rc = local.TimeOfDay.ToString(MxCultureInfo.GetFormatSpecifier(formatType, longFormat), culture); } else { rc = local.ToString(MxCultureInfo.GetFormatSpecifier(formatType, longFormat), culture); } } } catch (SkippedTimeException) { rc = "[error: invalid time]"; } catch (AmbiguousTimeException) { rc = "[error: ambiguous time]"; } catch (Exception e) { rc = e.Message; } } return(rc); }
public bool IsPastTime(ZonedDateTime dateTimeToCheck) { Instant currentInstance = Instant.FromDateTimeUtc(DateTime.UtcNow); ZonedDateTime currentDateTime = currentInstance.InZone(PolandZone); int comparisonResult = ZonedDateTime.Comparer.Local.Compare(currentDateTime, dateTimeToCheck); return(comparisonResult > 0); }
public Form1() { InitializeComponent(); ZonedDateTime zdt = now.InZone(timeZone); ZonedDateTime test = (Instant.FromDateTimeOffset(DateTime.Now)).InZone(timeZone); txtNodaTimeInstant.Text = now.ToString(); cmbTimeZone.DataSource = DateTimeZoneProviders.Tzdb.Ids; cmbTimeZone.SelectedItem = timeZone.Id; cmbCultures.DataSource = TzdbDateTimeZoneSource.Default.ZoneLocations.OrderBy(o => o.ZoneId).ToList(); cmbCultures.DisplayMember = "ZoneId"; cmbCultures.DataSource = CultureInfo.GetCultures(CultureTypes.AllCultures & ~CultureTypes.SpecificCultures).ToList(); cmbCultures.DisplayMember = "DisplayName"; cmbCultures.SelectedItem = culture; updateFormattedDatetime(); }
public static string GetDateString(Instant dt, DateTimeZone?tz = null) { if (tz == null) { tz = Sydney; } return(dt.InZone(tz).ToString(@"dddd dd MMMM, yyyy", CultureInfo.InvariantCulture)); }
public static DateTime UTCToLocal(long utc) { DateTimeZone dtz = DateTimeZoneProviders.Tzdb.GetZoneOrNull( Properties.Settings.Default.AWSTimeZone); Instant utc2 = Instant.FromUnixTimeSeconds(utc); return(utc2.InZone(dtz).ToDateTimeUnspecified()); }
public ScheduleView() { IClock systemClock = SystemClock.Instance; Instant now = systemClock.GetCurrentInstant(); DateTimeZone tz = DateTimeZoneProviders.Tzdb.GetSystemDefault(); LocalDate today = now.InZone(tz).Date; MonthViewStartDate = tz.AtStartOfDay(today).ToInstant(); }
public async Task <int> sendSolarAndUtilityReport() { LOGGER.Info("Dad's Energy Reporter {0}", Assembly.GetExecutingAssembly().GetName().Version); LOGGER.Debug("Validating settings"); try { validateSettings(settings); } catch (SettingsException) { return(1); } Instant mostRecentReportBillingDate = Instant.FromDateTimeUtc(settings.mostRecentReportBillingDate); if (haveSentReportTooRecently(mostRecentReportBillingDate)) { LOGGER.Info( "Report was already created and sent for billing cycle ending on {0}, which is too recent. Not checking again now.", mostRecentReportBillingDate.InZone(DateTimeZoneProviders.Tzdb.GetSystemDefault()).Date); return(0); } try { LOGGER.Info("Logging in..."); await logIn(); LOGGER.Info("Logged in."); SolarAndUtilityReport report = await reportGenerator.generateReport(); if (haveAlreadySentReport(mostRecentReportBillingDate, report)) { LOGGER.Info("Report has already been sent for billing cycle ending on {0}, not sending again.", report.billingDate); return(0); } LOGGER.Info("Sending email report"); await emailSender.sendEmail(report, settings.reportRecipientEmails); settings.mostRecentReportBillingDate = report.billingDate.AtStartOfDayInZone(reportTimeZone).ToInstant().ToDateTimeUtc(); settings.save(); return(0); } catch (Exception e) { LOGGER.Error(e, "Aborted report generation due to exception"); return(1); } finally { LOGGER.Info("Logging out"); Task.WaitAll( ownerApiService.authentication.logOut(), options.skipUtility ? Task.CompletedTask : orangeRocklandService.authentication.logOut()); LOGGER.Info("Done"); } }
public async Task SnapshotRDS(Instant snapshotTime) { using AmazonRDSClient rdsClient = new AmazonRDSClient(); var date = snapshotTime.InZone(TimeExtensions.EasternTimeZone).LocalDateTime.Date; var dateString = date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); var random = Guid.NewGuid().ToString().Substring(0, 1); string snapName = "AdminSnap-" + dateString + "-" + random; CreateDBSnapshotRequest request = new CreateDBSnapshotRequest(snapName, _instanceName); await rdsClient.CreateDBSnapshotAsync(request, CancellationToken.None); }
/// <summary> /// Convert Instant to LocalDateTime in the specified timezone. /// /// Convert InstantUtil.Empty to LocalDateTimeUtil.Empty. /// /// Use timeZone = DateTimeZone.Utc for the UTC timezone. /// </summary> public static LocalDateTime ToLocalDateTime(this Instant value, DateTimeZone timeZone) { if (value == InstantUtil.Empty) { return(LocalDateTimeUtil.Empty); } else { return(value.InZone(timeZone).LocalDateTime); } }
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()); }
public Dat(ZoneInfo zoneInfo, Instant instantUtc) : this(zoneInfo) { var k = instantUtc.InZone(ZoneInfo.Zone(), ZoneInfo.CalendarSystem()); Year = k.Year; Month = k.Month; Day = k.Day; Hour = k.Hour; Minute = k.Minute; Second = k.Second; Millisecond = k.Millisecond; }
public String getInstantTime() { Instant s = SystemClock.Instance.Now; var dhaka = DateTimeZoneProviders.Tzdb["Asia/Bishkek"]; var ZoneTime = s.InZone(dhaka); String da = String.Format("{0}", ZoneTime); String[] removeZone = da.Split(' '); String removedZone = removeZone[0]; return(removedZone); }
static void Main() { // TZDB ID for Pacific time DateTimeZone zone = DateTimeZoneProviders.Tzdb["America/Los_Angeles"]; // SystemClock implements IClock; you'd normally inject it // for testability Instant now = SystemClock.Instance.Now; ZonedDateTime pacificNow = now.InZone(zone); Console.WriteLine(pacificNow); }
public async Task SnapshotRDS(Instant snapshotTime) { using (AmazonRDSClient rdsClient = new AmazonRDSClient()) { var date = snapshotTime.InZone(DateTimeZoneProviders.Tzdb.GetZoneOrNull("America/New_York")).LocalDateTime.Date; var dateString = date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); var random = Guid.NewGuid().ToString().Substring(0, 1); string snapName = "AdminSnap-" + dateString + "-" + random; CreateDBSnapshotRequest request = new CreateDBSnapshotRequest(snapName, _instanceName); await rdsClient.CreateDBSnapshotAsync(request, CancellationToken.None); } }
public static DateTime UtcToLocal(this DateTime utcDateTime, string zoneId) { if (utcDateTime.Kind != DateTimeKind.Utc) { throw new ArgumentException( $"{nameof(utcDateTime)} must have {nameof(utcDateTime.Kind)} == {DateTimeKind.Utc}"); } Instant instant = Instant.FromDateTimeUtc(utcDateTime); var tz = DateTimeZoneProviders.Tzdb[zoneId]; return(instant.InZone(tz).ToDateTimeUnspecified()); }
public TargetPlanner( JobsWithSchedulesQuery job, Instant forTargetDate, ILogger parentLogger = null) { this.job = job; targetDate = forTargetDate; logger = parentLogger; jobZone = DateTimeZoneProviders.Tzdb[job.ScheduleTimeZone]; var zonedDate = forTargetDate.InZone(jobZone).Date; analysis = DateTimeAnalysis.ForZonedTargetDate(zonedDate); }
/// <summary> /// Converts a UTC dateTime to Local dateTime in the ianaTimeZone /// </summary> /// <param name="dateTimeUtc"></param> /// <param name="ianaTimeZoneName"></param> /// <returns></returns> public static DateTime?ToLocalDateTime(this DateTime dateTimeUtc, string ianaTimeZoneName) { dateTimeUtc = DateTime.SpecifyKind(dateTimeUtc, DateTimeKind.Utc); DateTimeZone timeZone = DateTimeZoneProviders.Tzdb.GetZoneOrNull(ianaTimeZoneName); if (timeZone != null) { Instant instant = Instant.FromDateTimeUtc(dateTimeUtc); var zonedDateTime = instant.InZone(timeZone); return(zonedDateTime.ToDateTimeUnspecified()); } return(null); }
/// <summary> /// Converts a non-local-time DateTime to a local-time DateTime based on the /// specified timezone. The returned object will be of Unspecified DateTimeKind /// which represents local time agnostic to servers timezone. To be used when /// we want to convert UTC to local time somewhere in the world. /// </summary> /// <param name="dateTime">Non-local DateTime as UTC or Unspecified DateTimeKind.</param> /// <param name="timezone">Timezone name (in TZDB format).</param> /// <returns>Local DateTime as Unspecified DateTimeKind.</returns> public static DateTime ToZone(this DateTime dateTime, string timezone) { if (dateTime.Kind == DateTimeKind.Local) { throw new ArgumentException("Expected non-local kind of DateTime"); } var zone = DateTimeZoneProviders.Tzdb[timezone]; Instant instant = dateTime.ToInstant(); ZonedDateTime inZone = instant.InZone(zone); DateTime unspecified = inZone.ToDateTimeUnspecified(); return(unspecified); }
/// <summary> /// Adds the days taking into account DST. /// </summary> /// <param name="targetUtc">The target UTC.</param> /// <param name="timeZone">The time zone.</param> /// <param name="numberOfDays">The number of days.</param> /// <returns></returns> private DateTime AddDays(DateTime targetUtc, string timeZone, int numberOfDays) { Instant instant = Instant.FromDateTimeUtc(targetUtc); DateTimeZone timeZoneInfo = DateTimeZoneProviders.Tzdb[timeZone]; ZonedDateTime zoned = instant.InZone(timeZoneInfo); LocalDateTime updated = zoned.LocalDateTime.PlusDays(numberOfDays); // Adding a number of days ZonedDateTime updatedZoned = timeZoneInfo.AtLeniently(updated); return(updatedZoned.ToDateTimeUtc()); }
public static IEnumerable <LocalDate> ReverseMonthRange(Instant instant, DateTimeZone tz, int count) { LocalDate today = instant.InZone(tz).Date; int year = today.Year; int month = today.Month; for (int i = 0; i < count; i++) { var localDate = new LocalDate(year, month, 1).Minus(Period.FromDays(i)); year = localDate.Year; month = localDate.Month; yield return(localDate); } }
public static DateTime FromUtcToTimezone(this DateTime dateTime, DateTimeZone timezone) { EnsureArg.IsNotNull(timezone); if (dateTime.Kind != DateTimeKind.Utc) { dateTime = new DateTime(dateTime.Ticks, DateTimeKind.Utc); } Instant instant = Instant.FromDateTimeUtc(dateTime); var usersZonedDateTime = instant.InZone(timezone); return(usersZonedDateTime.ToDateTimeUnspecified()); }
public static TimeZoneAdjustedDateInfo GetTimeZoneAdjustedDateInfo(string userId, Instant instant) { using (var db = new TransafeRxEntities()) { var timeZone = DateTimeZoneProviders.Tzdb.GetZoneOrNull(db.GetUserTimeZone(userId).SingleOrDefault() ?? "UTC"); return(new TimeZoneAdjustedDateInfo { DateUTC = instant.ToDateTimeUtc(), DateDTO = instant.InZone(timeZone).ToDateTimeOffset(), DateCTZ = timeZone.Id }); } }
public void Convert_Now_ToLocal() { Instant now = SystemClock.Instance.GetCurrentInstant(); DateTimeZone tz = DateTimeZoneProviders.Tzdb.GetZoneOrNull("Europe/London"); //DateTimeZone tz = DateTimeZoneProviders.Tzdb.GetSystemDefault(); DateTimeZone bcl = DateTimeZoneProviders.Bcl.GetSystemDefault(); ZonedDateTime zdt = now.InZone(tz); Debug.WriteLine(now); Debug.WriteLine(tz); Debug.WriteLine(zdt); }
static void Main() { Instant now = SystemClock.Instance.Now; Console.WriteLine("now : {0}", now); ZonedDateTime utcNow = now.InUtc(); Console.WriteLine("utcNow : {0}", utcNow); var poland = DateTimeZoneProviders.Tzdb["Europe/Warsaw"]; var polandTime = now.InZone(poland); Console.WriteLine("in poland : {0}", polandTime); }
public void Update(Size availableSize, Instant firstVisibleDay) { ColumnWidth = LayoutHelper.RoundLayoutValue(availableSize.Width / ColumnsCount); if (DoubleUtil.GreaterThanOrClose(ColumnWidth * ColumnsCount, availableSize.Width) == true) { ColumnWidth = LayoutHelper.FloorLayoutValue(availableSize.Width / ColumnsCount); } RowsHeight = LayoutHelper.RoundLayoutValue(availableSize.Height / RowsCount); if (DoubleUtil.GreaterThanOrClose(RowsHeight * RowsCount, availableSize.Height) == true) { RowsHeight = LayoutHelper.FloorLayoutValue(availableSize.Height / RowsCount); } GridCellSize = new Size(ColumnWidth, RowsHeight); Bounds = LayoutHelper.RoundLayoutRect3(new Rect(0, 0, ColumnWidth * ColumnsCount, RowsHeight * RowsCount)); double columnOffset = 0; Grid = new MonthViewDay[RowsCount][]; IClock systemClock = SystemClock.Instance; Instant now = systemClock.GetCurrentInstant(); DateTimeZone tz = DateTimeZoneProviders.Tzdb.GetSystemDefault(); LocalDate today = now.InZone(tz).Date; ZonedDateTime currentDay = tz.AtStartOfDay(today); for (int rowIndex = 0; rowIndex < RowsCount; rowIndex++) { columnOffset = 0; Grid[rowIndex] = new MonthViewDay[ColumnsCount]; for (int columnIndex = 0; columnIndex < ColumnsCount; columnIndex++) { // ColumnWidth and RowHeight should be already layout rounded - so no need to round the rect bounds var day = new MonthViewDay(); day.GridCell = new Rect(columnIndex * ColumnWidth, rowIndex * RowsHeight, ColumnWidth, RowsHeight); var nextDay = currentDay.Plus(NodaTime.Duration.FromDays(1)); day.Day = new Interval(currentDay.ToInstant(), nextDay.ToInstant()); // may be we should use 23:59:99999 as end interval????? currentDay = nextDay; Grid[rowIndex][columnIndex] = day; } columnOffset += ColumnWidth; } }
public override LocalDateTime GetLocalDateTime(Instant instant) { return instant.InZone(DateTimeZoneProviders.Tzdb[City.Timezone]).LocalDateTime; }
public override string GetFormattedNameAndTimezone(Instant instant) { var timezoneAbbreviation = instant.InZone(DateTimeZoneProviders.Tzdb[City.Timezone]).GetZoneInterval().Name; return City.GetFormattedNameAndTimezone(timezoneAbbreviation); }