private TimeZoneInfo GetTimeZone(string tzName) { var timeZone = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? TimeZoneInfo.FindSystemTimeZoneById(tzName) : TimeZoneInfo.FindSystemTimeZoneById(TZConvert.IanaToWindows(tzName)); if (timeZone == null) { throw new ApplicationException("No timeZone found"); } return(timeZone); }
public static TimeZoneInfo ToTimeZoneInfo(string windowsOrIanaTimeZoneId) { try { // Try a direct approach first return(TimeZoneInfo.FindSystemTimeZoneById(windowsOrIanaTimeZoneId)); } catch { // We have to convert to the opposite platform //bool isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); //if (!isWindows) { timeZoneId = TZConvert.WindowsToIana(windowsOrIanaTimeZoneId); } var timeZoneId = TZConvert.IanaToWindows(windowsOrIanaTimeZoneId); return(TimeZoneInfo.FindSystemTimeZoneById(timeZoneId)); } }
public static string ToTimeZoneFormattedNoAbbreviation(DateTimeOffset original, string timeZoneId) { TimeZoneInfo istTZ = TZConvert.GetTimeZoneInfo(timeZoneId); DateTimeOffset temp = TimeZoneInfo.ConvertTime(original, istTZ); var convertedTime = original .Subtract(temp.Offset) .ToOffset(temp.Offset); string lang = CultureInfo.CurrentCulture.Name; // example: "en-US" var abbreviations = TZNames.GetAbbreviationsForTimeZone(timeZoneId, lang); return(String.Format("{0}", convertedTime.Date.ToShortDateString())); }
/// <summary> /// A simple function that takes a string and does a ToUpper /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> public SkillResponse FunctionHandler(SkillRequest input, ILambdaContext context) { // var serviceProvider = StartUp.InitialiseServices(); // _nepaliCalendarService = serviceProvider.GetService<INepaliCalendarService>(); var info = TZConvert.GetTimeZoneInfo("Nepal Standard Time"); var localServerTime = DateTimeOffset.Now; var localTime = TimeZoneInfo.ConvertTime(localServerTime, info); var nepaliDate = _nepaliCalendarService.GetNepaliDate(localTime.DateTime); return(MakeSkillResponse($"Nepali Date is {nepaliDate} and Time in Nepal is {localTime:hh:mm tt}", true)); }
public DateTime GetUTCTime(string time, string timezone) { TimeZoneInfo tzi = TZConvert.GetTimeZoneInfo("Eastern Standard Time"); Console.WriteLine(tzi); var t = DateTime.Parse("5pm"); var tz = TimeZoneInfo.FindSystemTimeZoneById("Pakistan Standard Time"); var tz2 = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"); var newtime = TimeZoneInfo.ConvertTime(t, tz, tz2); return(newtime); }
public FormattedString Format(EcmaValue date) { EnsureInitialized(); date = date == default ? DateConstructor.Now() : date.ToNumber(); if (date < MinTime || date > MaxTime) { throw new EcmaRangeErrorException("Invalid time value"); } TimeZoneInfo timezone = TZConvert.GetTimeZoneInfo(this.TimeZone); DateTime dt = unixEpochUtc.AddMilliseconds(date.ToInt64() + timezone.BaseUtcOffset.TotalMilliseconds); return(FormatDateTime(dt, format.Pattern)); }
public void ToNewTimeZone_InputUtcTime_Test(string fromTimeZoneId, string toTimeZoneId) { var toTimezoneId = TZConvert.GetTimeZoneInfo(toTimeZoneId); var fromTimeZone = TZConvert.GetTimeZoneInfo(fromTimeZoneId); var testDateTime = DateTime.UtcNow; var pcUtcOffset = toTimezoneId.GetUtcOffset(testDateTime); var timeZoneOffset = fromTimeZone.GetUtcOffset(testDateTime); var expectedTimeDifference = pcUtcOffset - timeZoneOffset; var resultantTime = testDateTime.ToNewTimeZone(fromTimeZoneId, toTimeZoneId); Assert.AreEqual(expectedTimeDifference, resultantTime - testDateTime); }
public static DateTime?ConvertJstTimeFromUtc(this DateTime?utcDate) { var jstTimeZone = TZConvert.GetTimeZoneInfo("Tokyo Standard Time"); if (utcDate == null) { return(null); } var dateJst = TimeZoneInfo.ConvertTimeFromUtc((DateTime)utcDate, jstTimeZone); return(dateJst); }
public static DateTime ConvertTimeFromCoordinates(this DateTime date, double lat, double lon) { var tzIana = TimeZoneLookup.GetTimeZone(lat, lon).Result; #if Windows // Convert to Windows acceptable TimeZone tzIana = TZConvert.IanaToWindows(tzIana); #endif var tzInfo = TimeZoneInfo.FindSystemTimeZoneById(tzIana); var dt = DateTime.SpecifyKind(date, DateTimeKind.Utc); var convertedTime = TimeZoneInfo.ConvertTimeFromUtc(dt, tzInfo); return(convertedTime); }
public void LocalToServerTime_Test(string timeZoneId) { var thisComputerTimeZone = TimeZone.CurrentTimeZone; var specifiedTimeZone = TZConvert.GetTimeZoneInfo(timeZoneId); var testDateTime = new DateTime(2006, 6, 12, 11, 0, 0); var pcUtcOffset = thisComputerTimeZone.GetUtcOffset(testDateTime); var timeZoneOffset = specifiedTimeZone.GetUtcOffset(testDateTime); var expectedTimeDifference = pcUtcOffset - timeZoneOffset; var expectedTime = testDateTime.LocalTimeToServerTime(timeZoneId); Assert.AreEqual(expectedTimeDifference, expectedTime - testDateTime); }
public async Task SetGlobal(GlobalSettings global) { if (global.LoginExpireAfterDays <= 0) { throw new Exception($"{nameof(global.LoginExpireAfterDays)} must be greater than zero"); } if (string.IsNullOrEmpty(global.TimeZoneId)) { throw new Exception($"{nameof(global.TimeZoneId)} must be set"); } var tz = TZConvert.GetTimeZoneInfo(global.TimeZoneId); if (tz == null) { throw new Exception($"{nameof(global.TimeZoneId)} is invalid"); } ((await _globalSettings.Find("Clickatell")) ?? _globalSettings.Add(new GlobalSetting { Key = "Clickatell" })).Value = JsonConvert.SerializeObject(global.Clickatell); ((await _globalSettings.Find("Email")) ?? _globalSettings.Add(new GlobalSetting { Key = "Email" })).Value = JsonConvert.SerializeObject(global.Email); ((await _globalSettings.Find("AuthenticationGroup")) ?? _globalSettings.Add(new GlobalSetting { Key = "AuthenticationGroup" })).Value = JsonConvert.SerializeObject(global.AuthenticationGroup); ((await _globalSettings.Find("SlackToken")) ?? _globalSettings.Add(new GlobalSetting { Key = "SlackToken" })).Value = JsonConvert.SerializeObject(global.SlackToken); ((await _globalSettings.Find("Url")) ?? _globalSettings.Add(new GlobalSetting { Key = "Url" })).Value = JsonConvert.SerializeObject(global.Url); ((await _globalSettings.Find("ResultRetentionMonths")) ?? _globalSettings.Add(new GlobalSetting { Key = "ResultRetentionMonths" })).Value = JsonConvert.SerializeObject(global.ResultRetentionMonths); ((await _globalSettings.Find("ResultAggregateDays")) ?? _globalSettings.Add(new GlobalSetting { Key = "ResultAggregateDays" })).Value = JsonConvert.SerializeObject(global.ResultAggregateDays); ((await _globalSettings.Find("CleanupSchedule")) ?? _globalSettings.Add(new GlobalSetting { Key = "CleanupSchedule" })).Value = JsonConvert.SerializeObject(global.CleanupSchedule); ((await _globalSettings.Find("LoginExpireAfterDays")) ?? _globalSettings.Add(new GlobalSetting { Key = "LoginExpireAfterDays" })).Value = JsonConvert.SerializeObject(global.LoginExpireAfterDays); ((await _globalSettings.Find("TimeZoneId")) ?? _globalSettings.Add(new GlobalSetting { Key = "TimeZoneId" })).Value = JsonConvert.SerializeObject(global.TimeZoneId); ((await _globalSettings.Find("CountryCode")) ?? _globalSettings.Add(new GlobalSetting { Key = "CountryCode" })).Value = JsonConvert.SerializeObject(global.CountryCode); await _globalSettings.SaveChangesAsync(); }
public ScheduleController(IScheduleService service, IHttpContextAccessor accessor) { _service = service; _accessor = accessor; var zoneId = _accessor.HttpContext.Request.Cookies["tzTime"] ?? "Asia/Taipei"; _customerTimezone = TimeZoneInfo.FindSystemTimeZoneById(TZConvert.IanaToWindows(zoneId)); _systemTimezone = TimeZoneInfo.Local; var cultureId = _accessor.HttpContext.Request.Cookies["culture"] ?? "zh-TW"; _culture = CultureInfo.CreateSpecificCulture(cultureId); }
private async Task <Data.Shared.Models.Photo> UploadPhoto(IFormFile photo, PhotoType type, string userId, bool storeLocation) { var blobpath = Guid.NewGuid().ToString(); var fileInfo = new FileInfo(photo.FileName); var name = "original" + fileInfo.Extension; var result = await _blobService.UploadPhotoAsync(photo, userId, Path.Combine(blobpath, name)); if (result != null) { var location = GetLocationFromMetadata(result.Metadata); var(height, width) = GetDimensionsFromMetadata(result.Metadata); var timezone = TimeZoneInfo.Local; if (location != null && location.Latitude.HasValue && location.Longitude.HasValue) { var zone = TimeZoneLookup.GetTimeZone(location.Latitude.Value, location.Longitude.Value); timezone = TZConvert.GetTimeZoneInfo(zone.Result); } DateTime?dateTaken = null; if (result.Metadata.TryGetValue(Constants.DateTaken, out var dateTakenEntry)) { if (!string.IsNullOrEmpty(dateTakenEntry)) { if (DateTime.TryParse(dateTakenEntry, out var dateTakenValue)) { dateTaken = TimeZoneInfo.ConvertTimeToUtc(dateTakenValue, timezone); } } } return(new Data.Shared.Models.Photo { Filename = name, BlobPath = blobpath, BlobPathRoot = _blobStorageRoot, Type = type, UserId = userId, ContentType = result.ContentType, Location = storeLocation ? location : null, Height = height, Width = width, DateTaken = dateTaken, DateCreated = DateTime.UtcNow, CreatedBy = userId }); } return(null); }
public async Task <TimeZoneInfo> GetTimeZone() { using (var scope = _container.CreateScope()) { var settingsHelper = scope.ServiceProvider.GetRequiredService <ISettingsHelper>(); var global = await settingsHelper.GetGlobal(); if (string.IsNullOrEmpty(global.TimeZoneId)) { throw new Exception("TimeZoneId is invalid"); } return(TZConvert.GetTimeZoneInfo(global.TimeZoneId)); } }
public static TimeZoneInfo GetTimeZoneInfoOnGeoLocation(double latitude, double longitude) { TimeZoneInfo timeZoneInfo = null; try { TimeZoneResult timeZoneResult = TimeZoneLookup.GetTimeZone(latitude, longitude); timeZoneInfo = TZConvert.GetTimeZoneInfo(timeZoneResult.Result); } catch { } return(timeZoneInfo); }
public static string GetOpenStatus(Place place) { var tzIana = TimeZoneLookup.GetTimeZone(place.Latitude, place.Longitude).Result; var tzMs = TZConvert.IanaToWindows(tzIana); var tzInfo = TimeZoneInfo.FindSystemTimeZoneById(tzMs); var now = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tzInfo); var isWeekend = now.DayOfWeek == DayOfWeek.Saturday || now.DayOfWeek == DayOfWeek.Sunday; return(!isWeekend & now.TimeOfDay > place.OpenTime && now.TimeOfDay < place.CloseTime || isWeekend & now.TimeOfDay > place.OpenTimeWeekend && now.TimeOfDay < place.CloseTimeWeekend ? String.Empty : "🔒 "); }
public void Can_Convert_Canonical() { string result1 = TZConvert.WindowsToIana("US Eastern Standard Time"); Assert.Equal("America/Indiana/Indianapolis", result1); string result2 = TZConvert.WindowsToIana("India Standard Time"); Assert.Equal("Asia/Kolkata", result2); string result3 = TZConvert.WindowsToIana("Nepal Standard Time"); Assert.Equal("Asia/Kathmandu", result3); }
public void Can_Convert_Non_Canonical() { string result1 = TZConvert.WindowsToIana("US Eastern Standard Time", resolveCanonical: false); Assert.Equal("America/Indianapolis", result1); string result2 = TZConvert.WindowsToIana("India Standard Time", resolveCanonical: false); Assert.Equal("Asia/Calcutta", result2); string result3 = TZConvert.WindowsToIana("Nepal Standard Time", resolveCanonical: false); Assert.Equal("Asia/Katmandu", result3); }
public void ShouldRespectTimeZoneForFirstFireTime() { var tz = TZConvert.GetTimeZoneInfo("E. South America Standard Time"); var dailyTrigger = (IOperableTrigger)TriggerBuilder.Create() .StartAt(new DateTime(2017, 1, 4, 15, 0, 0, DateTimeKind.Utc)) .WithCalendarIntervalSchedule(x => x .WithIntervalInDays(2) .InTimeZone(tz)) .Build(); var firstFireTime = TriggerUtils.ComputeFireTimes(dailyTrigger, null, 1).First(); Assert.That(firstFireTime, Is.EqualTo(new DateTimeOffset(2017, 1, 4, 13, 0, 0, TimeSpan.FromHours(-2)))); }
static TimeZoneInfo TryParse(string timezoneId, bool convertFromIana = false) { try { return(TimeZoneInfo.FindSystemTimeZoneById( convertFromIana ? TZConvert.IanaToWindows(timezoneId) : timezoneId)); } catch { return(null); } }
/// <summary> /// A helper to get corresponding windows timezone for input Iana timezone /// </summary> /// <param name="timezoneAbbreviation"></param> /// <returns>The windows timezone name string. Returns empty string if invalid</returns> public static string GetWindowsTimeZoneName(string timezoneAbbreviation) { string standardWindowsTime; try { standardWindowsTime = TZConvert.IanaToWindows(timezoneAbbreviation); } catch { standardWindowsTime = string.Empty; } return(standardWindowsTime); }
public static TimeZoneInfo LocalTimeZone(this Models.Patrol patrol) { TimeZoneInfo timeZone; if (!string.IsNullOrEmpty(patrol.TimeZone)) { timeZone = TZConvert.GetTimeZoneInfo(patrol.TimeZone); } else { timeZone = TZConvert.GetTimeZoneInfo("Eastern Standard Time"); } return(timeZone); }
public void Can_Convert_Windows_Zones_To_Iana_Regional_Zones() { var result1 = TZConvert.WindowsToIana("Central Europe Standard Time", "CZ"); Assert.Equal("Europe/Prague", result1); var result2 = TZConvert.WindowsToIana("Central Europe Standard Time", "foo"); Assert.Equal("Europe/Budapest", result2); var result3 = TZConvert.WindowsToIana("Central Europe Standard Time"); Assert.Equal("Europe/Budapest", result3); }
public static TimeZoneInfo GetTimeZoneInfo(string zoneName) { TimeZoneInfo timeZoneInfo; try { timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(zoneName); } catch (Exception) { timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(TZConvert.WindowsToIana(zoneName)); } return(timeZoneInfo); }
public static DateTime ToLocalTime(this DateTime utcDate, string ianaTimezone) { utcDate.GuardAgainstInvalid(d => d != DateTime.MinValue, nameof(utcDate)); utcDate.GuardAgainstInvalid(d => d.Kind == DateTimeKind.Utc, nameof(utcDate), Resources.DateTimeExtensions_DateTimeIsNotUtc); ianaTimezone.GuardAgainstNull(nameof(ianaTimezone)); if (!TZConvert.TryGetTimeZoneInfo(ianaTimezone, out var timeZoneInfo)) { throw new ArgumentOutOfRangeException(Resources.DateTimeExtensions_InvalidTimezone); } return(TimeZoneInfo.ConvertTimeFromUtc(utcDate, timeZoneInfo)); }
public static TimeZoneInfo GetTimeZoneByAspNetHeader(IHttpContextAccessor httpContextAccessor, string headerName) { var httpContext = httpContextAccessor.HttpContext; try { var timezone = httpContext.Request.Headers[headerName]; return(TZConvert.GetTimeZoneInfo(timezone)); } catch (Exception) { return(DefaultTimeZone); } }
/// <summary> /// Initializes a new instance of the <see cref="TimeConfigurationForm" /> class. /// </summary> public TimeConfigurationForm(Configuration.Time timeConfig) { InitializeComponent(); TimeConfig = timeConfig; if (TimeConfig.TimeServerSourceType == Configuration.TimeServerSource.Auto) { rbAuto.Checked = true; } else if (TimeConfig.TimeServerSourceType == Configuration.TimeServerSource.Manual) { rbManual.Checked = true; } else { rbNone.Checked = true; } var timeZone = TimeZoneInfo.Utc; if (!string.IsNullOrEmpty(TimeConfig.TimeZone)) { timeZone = TZConvert.GetTimeZoneInfo(TimeConfig.TimeZone); } var timeZones = TimeZoneInfo.GetSystemTimeZones(); foreach (var zone in timeZones) { var cbxItem = new ComboboxItem { Text = zone.DisplayName, Value = zone }; cbxTimeZone.Items.Add(cbxItem); if (timeZone.Id == zone.Id) { cbxTimeZone.SelectedItem = cbxItem; } } if (cbxTimeZone.SelectedItem == null) { cbxTimeZone.SelectedIndex = 0; } foreach (var host in TimeConfig.ExternalTimeServers) { lvExternalTimeServers.Items.Add(new ListViewItem(host)); } }
public static Event ToGoogleEvent(this IAppointment appointment, int?sequence = null, string uniqueId = null) { if (appointment.Schedule == null) { throw new ArgumentException("Appointment does not contain schedule"); } var ev = new Event { Transparency = appointment.Busy ? "opaque" : "transparent", Summary = appointment.Subject, Location = appointment.Location, ICalUID = uniqueId, Sequence = sequence, Status = appointment.Confirmed ? "confirmed" : "tentative", Reminders = new Event.RemindersData { UseDefault = false, }, Recurrence = appointment.Schedule.ToRfc5545Rules().ToList(), }; if (appointment.Schedule.AllDay) { ev.Start = new EventDateTime { Date = appointment.Schedule.Start.Date.ToString("yyyy-MM-dd"), }; ev.End = new EventDateTime { Date = appointment.Schedule.End.Date.ToString("yyyy-MM-dd"), }; } else { ev.Start = new EventDateTime { DateTime = appointment.Schedule.Start, TimeZone = TZConvert.WindowsToIana(appointment.Schedule.StartTimeZone.Id), }; ev.End = new EventDateTime { DateTime = appointment.Schedule.End, TimeZone = TZConvert.WindowsToIana(appointment.Schedule.EndTimeZone.Id), }; } return(ev); }
public static async void Run([TimerTrigger("0 0 * * * *")] TimerInfo myTimer, ILogger log) { TimeZoneInfo jstTimeZone = TZConvert.GetTimeZoneInfo("Tokyo Standard Time"); DateTime utcTime = DateTime.UtcNow; DateTime jstTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, jstTimeZone); log.LogInformation($"C# Timer trigger function executed at: {jstTime}"); string url = "https://qiita.com/api/v2/users/" + Parameter.getQiitaUserName() + "/items"; string json = await GetJson(url); var settings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, MissingMemberHandling = MissingMemberHandling.Ignore }; List <QiitaInformationModel> models = JsonConvert.DeserializeObject <List <QiitaInformationModel> >(json, settings); string getViewsCountUrl; foreach (var model in models) { getViewsCountUrl = "https://qiita.com/api/v2/items/" + model.Id; model.PageViewsCount = JsonConvert.DeserializeObject <QiitaInformationModel>(await GetJson(getViewsCountUrl)).PageViewsCount; log.LogInformation($"title: {model.Title}"); log.LogInformation($"views: {model.PageViewsCount}"); } var connectionString = Parameter.getConnectionString(); using (var connection = new SqlConnection(connectionString)) { connection.Open(); try { Database.checkMasterData(models, log, connection); Database.saveData(models, jstTime, log, connection); } catch (Exception exception) { log.LogInformation(exception.Message); throw; } finally { connection.Close(); } } }
public static async Task <UserInfo> UpdateUserInfo(UserInfo updatedUserInfo) { if (ProgenyService.Online()) { var client = new HttpClient(); client.BaseAddress = new Uri(Constants.ProgenyApiUrl); string accessToken = await UserService.GetAuthAccessToken(); client.SetBearerToken(accessToken); try { var result = await client.PutAsync("api/userinfo/" + updatedUserInfo.UserId, new StringContent(JsonConvert.SerializeObject(updatedUserInfo), Encoding.UTF8, "application/json")).ConfigureAwait(false); if (result.IsSuccessStatusCode) { string resultString = await result.Content.ReadAsStringAsync(); UserInfo resultUserInfo = JsonConvert.DeserializeObject <UserInfo>(resultString); await SecureStorage.SetAsync(Constants.UserNameKey, resultUserInfo.UserName); await SecureStorage.SetAsync(Constants.UserFirstNameKey, resultUserInfo.FirstName); await SecureStorage.SetAsync(Constants.UserMiddleNameKey, resultUserInfo.MiddleName); await SecureStorage.SetAsync(Constants.UserLastNameKey, resultUserInfo.LastName); try { TimeZoneInfo.FindSystemTimeZoneById(resultUserInfo.Timezone); } catch (Exception) { resultUserInfo.Timezone = TZConvert.WindowsToIana(resultUserInfo.Timezone); } await SecureStorage.SetAsync(Constants.UserTimezoneKey, resultUserInfo.Timezone); return(resultUserInfo); } } catch (Exception ex) { Debug.WriteLine(ex.Message); return(new UserInfo()); } } return(new UserInfo()); }