/// <summary> /// Sets the time on the specified DateTime value using the specified time zone. /// </summary> /// <param name = "datetimeOff">The base date.</param> /// <param name = "timespan">The TimeSpan to be applied.</param> /// <param name = "localTimeZone">The local time zone.</param> /// <returns>/// The DateTimeOffset including the new time value/// </returns> public static DateTimeOffset SetTime(this DateTimeOffset datetimeOff, TimeSpan timespan, TimeZoneInfo localTimeZone) { var localDate = datetimeOff.ToLocalDateTime(localTimeZone); localDate.SetTime(timespan); return localDate.ToDateTimeOffset(localTimeZone); }
public static TimeZoneInfo[] GetZones(DBHelper dbh, int langId) { List<TimeZoneInfo> list = new List<TimeZoneInfo>(); using (IDataReader reader = dbh.RunSPDataReader("TimeZonesGet", DBHelper.MP("@LanguageId", SqlDbType.Int, langId))) { while (reader.Read()) { TimeZoneInfo item = new TimeZoneInfo(); item.TimeZoneId = (int)reader["TimeZoneId"]; item.Bias = (int)reader["Bias"]; item.StandardBias = (int)reader["StandardBias"]; item.DaylightBias = (int)reader["DaylightBias"]; item.DaylightMonth = (int)reader["DaylightMonth"]; item.DaylightDayOfWeek = (int)reader["DaylightDayOfWeek"]; item.DaylightWeek = (int)reader["DaylightWeek"]; item.DaylightHour = (int)reader["DaylightHour"]; item.StandardMonth = (int)reader["StandardMonth"]; item.StandardDayOfWeek = (int)reader["StandardDayOfWeek"]; item.StandardWeek = (int)reader["StandardWeek"]; item.StandardHour = (int)reader["StandardHour"]; list.Add(item); } } return list.ToArray(); }
public static DateTimeOffset Add(this DateTime dateTime, TimeSpan timeSpan, TimeZoneInfo timeZone, TimeZoneOffsetResolver resolver) { var utc = dateTime.Kind == DateTimeKind.Unspecified ? resolver.Invoke(dateTime, timeZone).UtcDateTime : dateTime.ToUniversalTime(); var dt = utc.Add(timeSpan); return TimeZoneInfo.ConvertTime(dt, timeZone); }
/// <summary> /// This class is a singleton with a one-time initialisation. /// Return a correctly initialised TimeZoneInfo. /// </summary> /// <returns></returns> public static TimeZoneInfo GetTimeZoneInfo() { if (_instance == null) { _instance = new TimeZoneInfo(); _instance.Initialise(); } return _instance; }
public static DateTimeOffset Default(DateTime dt, TimeZoneInfo timeZone) { if (dt.Kind != DateTimeKind.Unspecified) { var dto = new DateTimeOffset(dt); return TimeZoneInfo.ConvertTime(dto, timeZone); } if (timeZone.IsAmbiguousTime(dt)) { var earlierOffset = timeZone.GetUtcOffset(dt.AddDays(-1)); return new DateTimeOffset(dt, earlierOffset); } if (timeZone.IsInvalidTime(dt)) { var earlierOffset = timeZone.GetUtcOffset(dt.AddDays(-1)); var laterOffset = timeZone.GetUtcOffset(dt.AddDays(1)); var transitionGap = laterOffset - earlierOffset; return new DateTimeOffset(dt.Add(transitionGap), laterOffset); } return new DateTimeOffset(dt, timeZone.GetUtcOffset(dt)); }
protected override void ProcessRecord() { // make sure we've got fresh data, in case the requested time zone was added // to the system (registry) after our process was started TimeZoneHelper.ClearCachedData(); // acquire a TimeZoneInfo if one wasn't supplied. if (this.ParameterSetName.Equals("Id", StringComparison.OrdinalIgnoreCase)) { try { InputObject = TimeZoneInfo.FindSystemTimeZoneById(Id); } #if CORECLR // TimeZoneNotFoundException is thrown by TimeZoneInfo, but not // publicly visible (so can't be caught), so for now we're catching // the parent exception time. This should be removed once the more // specific exception is available. catch (Exception e) #else catch (TimeZoneNotFoundException e) #endif { ThrowTerminatingError(new ErrorRecord( e, TimeZoneHelper.TimeZoneNotFoundError, ErrorCategory.InvalidArgument, "Id")); } } else if (this.ParameterSetName.Equals("Name", StringComparison.OrdinalIgnoreCase)) { // lookup the time zone name and make sure we have one (and only one) match TimeZoneInfo[] timeZones = TimeZoneHelper.LookupSystemTimeZoneInfoByName(Name); if (0 == timeZones.Length) { string message = string.Format(CultureInfo.InvariantCulture, TimeZoneResources.TimeZoneNameNotFound, Name); #if CORECLR // Because .NET Core does not currently expose the TimeZoneNotFoundException // we need to throw the more generic parent exception class for the time being. // This should be removed once the correct exception class is available. Exception e = new Exception(message); #else Exception e = new TimeZoneNotFoundException(message); #endif ThrowTerminatingError(new ErrorRecord(e, TimeZoneHelper.TimeZoneNotFoundError, ErrorCategory.InvalidArgument, "Name")); } else if (1 < timeZones.Length) { string message = string.Format(CultureInfo.InvariantCulture, TimeZoneResources.MultipleMatchingTimeZones, Name); ThrowTerminatingError(new ErrorRecord( new PSArgumentException(message, "Name"), TimeZoneHelper.MultipleMatchingTimeZonesError, ErrorCategory.InvalidArgument, "Name")); } else { InputObject = timeZones[0]; } } else // ParameterSetName == "InputObject" { try { // a TimeZoneInfo object was supplied, so use it to make sure we can find // a backing system time zone, otherwise it's an error condition InputObject = TimeZoneInfo.FindSystemTimeZoneById(InputObject.Id); } #if CORECLR // TimeZoneNotFoundException is thrown by TimeZoneInfo, but not // publicly visible (so can't be caught), so for now we're catching // the parent exception time. This should be removed once the more // specific exception is available. catch (Exception e) #else catch (TimeZoneNotFoundException e) #endif { ThrowTerminatingError(new ErrorRecord( e, TimeZoneHelper.TimeZoneNotFoundError, ErrorCategory.InvalidArgument, "InputObject")); } } if (ShouldProcess(TimeZoneTarget)) { bool acquireAccess = false; try { // check to see if permission to set the time zone is already enabled for this process if (!HasAccess) { // acquire permissions to set the timezone SetAccessToken(true); acquireAccess = true; } } catch (Win32Exception e) { ThrowTerminatingError(new ErrorRecord(e, TimeZoneHelper.InsufficientPermissionsError, ErrorCategory.PermissionDenied, null)); } try { // construct and populate a new DYNAMIC_TIME_ZONE_INFORMATION structure NativeMethods.DYNAMIC_TIME_ZONE_INFORMATION dtzi = new NativeMethods.DYNAMIC_TIME_ZONE_INFORMATION(); dtzi.Bias -= (int)InputObject.BaseUtcOffset.TotalMinutes; dtzi.StandardName = InputObject.StandardName; dtzi.DaylightName = InputObject.DaylightName; dtzi.TimeZoneKeyName = InputObject.Id; // Request time zone transition information for the current year NativeMethods.TIME_ZONE_INFORMATION tzi = new NativeMethods.TIME_ZONE_INFORMATION(); if (!NativeMethods.GetTimeZoneInformationForYear((ushort)DateTime.Now.Year, ref dtzi, ref tzi)) { ThrowWin32Error(); } // copy over the transition times dtzi.StandardBias = tzi.StandardBias; dtzi.StandardDate = tzi.StandardDate; dtzi.DaylightBias = tzi.DaylightBias; dtzi.DaylightDate = tzi.DaylightDate; // set the new local time zone for the system if (!NativeMethods.SetDynamicTimeZoneInformation(ref dtzi)) { ThrowWin32Error(); } #if !CORECLR // broadcast a WM_SETTINGCHANGE notification message to all top-level windows so that they // know to update their notion of the current system time (and time zone) if applicable int result = 0; NativeMethods.SendMessageTimeout((IntPtr)NativeMethods.HWND_BROADCAST, NativeMethods.WM_SETTINGCHANGE, (IntPtr)0, "intl", NativeMethods.SMTO_ABORTIFHUNG, 5000, ref result); #endif // clear the time zone data or this PowerShell session // will not recognize the new time zone settings TimeZoneHelper.ClearCachedData(); if (PassThru.IsPresent) { // return the TimeZoneInfo object for the (new) current local time zone WriteObject(TimeZoneInfo.Local); } } catch (Win32Exception e) { ThrowTerminatingError(new ErrorRecord(e, TimeZoneHelper.SetTimeZoneFailedError, ErrorCategory.FromStdErr, null)); } finally { if (acquireAccess) { // reset the permissions SetAccessToken(false); } } } else { if (PassThru.IsPresent) { // show the user the time zone settings that would have been used. WriteObject(InputObject); } } }
public static DateTimeOffset AddHours(this DateTime dateTime, double hours, TimeZoneInfo timeZone, TimeZoneOffsetResolver resolver) { return dateTime.Add(TimeSpan.FromHours(hours), timeZone, resolver); }
/// <summary> /// Gets a <see cref="DateTimeOffset"/> object that is set to the current date, time, /// and offset from Coordinated Universal Time (UTC) in the specified time zone. /// </summary> /// <param name="timeZoneInfo">The <see cref="TimeZoneInfo"/> instance.</param> /// <returns>The current <see cref="DateTimeOffset"/> for the specified time zone.</returns> public static DateTimeOffset NowInTimeZone(TimeZoneInfo timeZoneInfo) { // TODO: Propose placing this method directly in the System.DateTimeOffset struct DateTimeOffset utcNow = DateTimeOffset.UtcNow; return TimeZoneInfo.ConvertTime(utcNow, timeZoneInfo); }
public Task <bool> GetBigJson() => this.JsonResponseAsync(Enumerable.Range(1, 100).Select(x => new { x, y = TimeZoneInfo.GetSystemTimeZones() .Select(z => new { z.StandardName, z.DisplayName }), }));
private static DateTimeOffset AddByDate(DateTimeOffset dateTimeOffset, Func<DateTime, DateTime> operation, TimeZoneInfo timeZone, TimeZoneOffsetResolver resolver) { var dto = TimeZoneInfo.ConvertTime(dateTimeOffset, timeZone); var dt = operation.Invoke(dto.DateTime); return resolver.Invoke(dt, timeZone); }
public static DateTimeOffset AddMonths(this DateTimeOffset dateTimeOffset, int months, TimeZoneInfo timeZone, TimeZoneOffsetResolver resolver) { return AddByDate(dateTimeOffset, dt => dt.AddMonths(months), timeZone, resolver); }
/// <summary> /// Initializes a new instance of the <see cref="ExchangeServiceBase"/> class. /// </summary> /// <param name="requestedServerVersion">The requested server version.</param> /// <param name="timeZone">The time zone to which the service is scoped.</param> internal ExchangeServiceBase(ExchangeVersion requestedServerVersion, TimeZoneInfo timeZone) : this(timeZone) { this.requestedServerVersion = requestedServerVersion; }
public static DateTimeOffset AddYears(this DateTime dateTime, int years, TimeZoneInfo timeZone) { return AddByDate(dateTime, dt => dt.AddYears(years), timeZone, TimeZoneOffsetResolvers.Default); }
private static DateTime ConvertTimeWithAmbiguousTimeHandling(DateTime val, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone) { if (!sourceTimeZone.IsInvalidTime(val)) { return(TimeZoneInfo.ConvertTime(val, sourceTimeZone, destinationTimeZone)); } //because ShipStation operates in PST/PDT: it's still possible to have ambiguous datetime even if client sends/receives data in UTC var ambiguousTimeRule = sourceTimeZone.GetAdjustmentRules() .First(x => x.DateStart <= val && val <= x.DateEnd); val = val.Add(new TimeSpan(-ambiguousTimeRule.DaylightDelta.Ticks)); val = TimeZoneInfo.ConvertTime(val, sourceTimeZone, destinationTimeZone); return(val.Add(ambiguousTimeRule.DaylightDelta)); }
/// <summary> /// Initializes a new instance of the <see cref="ExchangeServiceBase"/> class. /// </summary> /// <param name="timeZone">The time zone to which the service is scoped.</param> internal ExchangeServiceBase(TimeZoneInfo timeZone) { this.timeZone = timeZone; this.UseDefaultCredentials = true; }
public SpecificTimeZoneDateConverter(string dateFormat, TimeZoneInfo timeZoneInfo) { _dateFormat = dateFormat; _timeZoneInfo = timeZoneInfo; }
/// <summary> /// Prepare system info model /// </summary> /// <param name="model">System info model</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the system info model /// </returns> public virtual async Task<SystemInfoModel> PrepareSystemInfoModelAsync(SystemInfoModel model) { if (model == null) throw new ArgumentNullException(nameof(model)); model.NopVersion = NopVersion.FULL_VERSION; model.ServerTimeZone = TimeZoneInfo.Local.StandardName; model.ServerLocalTime = DateTime.Now; model.UtcTime = DateTime.UtcNow; model.CurrentUserTime = await _dateTimeHelper.ConvertToUserTimeAsync(DateTime.Now); model.HttpHost = _httpContextAccessor.HttpContext.Request.Headers[HeaderNames.Host]; //ensure no exception is thrown try { model.OperatingSystem = Environment.OSVersion.VersionString; model.AspNetInfo = RuntimeInformation.FrameworkDescription; model.IsFullTrust = AppDomain.CurrentDomain.IsFullyTrusted; } catch { // ignored } foreach (var header in _httpContextAccessor.HttpContext.Request.Headers) { model.Headers.Add(new SystemInfoModel.HeaderModel { Name = header.Key, Value = header.Value }); } foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { var loadedAssemblyModel = new SystemInfoModel.LoadedAssembly { FullName = assembly.FullName }; //ensure no exception is thrown try { loadedAssemblyModel.Location = assembly.IsDynamic ? null : assembly.Location; loadedAssemblyModel.IsDebug = assembly.GetCustomAttributes(typeof(DebuggableAttribute), false) .FirstOrDefault() is DebuggableAttribute attribute && attribute.IsJITOptimizerDisabled; //https://stackoverflow.com/questions/2050396/getting-the-date-of-a-net-assembly //we use a simple method because the more Jeff Atwood's solution doesn't work anymore //more info at https://blog.codinghorror.com/determining-build-date-the-hard-way/ loadedAssemblyModel.BuildDate = assembly.IsDynamic ? null : (DateTime?)TimeZoneInfo.ConvertTimeFromUtc(_fileProvider.GetLastWriteTimeUtc(assembly.Location), TimeZoneInfo.Local); } catch { // ignored } model.LoadedAssemblies.Add(loadedAssemblyModel); } var currentStaticCacheManagerName = _staticCacheManager.GetType().Name; if (_appSettings.DistributedCacheConfig.Enabled) currentStaticCacheManagerName += $"({await _localizationService.GetLocalizedEnumAsync(_appSettings.DistributedCacheConfig.DistributedCacheType)})"; model.CurrentStaticCacheManager = currentStaticCacheManagerName; model.AzureBlobStorageEnabled = _appSettings.AzureBlobConfig.Enabled; return model; }
/// <summary> /// Implementation of the ProcessRecord method for Get-TimeZone /// </summary> protected override void ProcessRecord() { // make sure we've got the latest time zone settings TimeZoneHelper.ClearCachedData(); if (this.ParameterSetName.Equals("ListAvailable", StringComparison.OrdinalIgnoreCase)) { // output the list of all available time zones WriteObject(TimeZoneInfo.GetSystemTimeZones(), true); } else if (this.ParameterSetName.Equals("Id", StringComparison.OrdinalIgnoreCase)) { // lookup each time zone id foreach (string tzid in Id) { try { WriteObject(TimeZoneInfo.FindSystemTimeZoneById(tzid)); } #if CORECLR // TimeZoneNotFoundException is thrown by TimeZoneInfo, but not // publicly visible (so can't be caught), so for now we're catching // the parent exception time. This should be removed once the more // specific exception is available. catch (Exception e) #else catch (TimeZoneNotFoundException e) #endif { WriteError(new ErrorRecord(e, TimeZoneHelper.TimeZoneNotFoundError, ErrorCategory.InvalidArgument, "Id")); } } } else // ParameterSetName == "Name" { if (null != Name) { // lookup each time zone name (or wildcard pattern) foreach (string tzname in Name) { TimeZoneInfo[] timeZones = TimeZoneHelper.LookupSystemTimeZoneInfoByName(tzname); if (0 < timeZones.Length) { // manually process each object in the array, so if there is only a single // entry then the returned type is TimeZoneInfo and not TimeZoneInfo[], and // it can be pipelined to Set-TimeZone more easily foreach (TimeZoneInfo timeZone in timeZones) { WriteObject(timeZone); } } else { string message = string.Format(CultureInfo.InvariantCulture, TimeZoneResources.TimeZoneNameNotFound, tzname); #if CORECLR // Because .NET Core does not currently expose the TimeZoneNotFoundException // we need to throw the more generic parent exception class for the time being. // This should be removed once the correct exception class is available. Exception e = new Exception(message); #else Exception e = new TimeZoneNotFoundException(message); #endif WriteError(new ErrorRecord(e, TimeZoneHelper.TimeZoneNotFoundError, ErrorCategory.InvalidArgument, "Name")); } } } else { // return the current system local time zone WriteObject(TimeZoneInfo.Local); } } }
public static DateTimeOffset AddMinutes(this DateTime dateTime, double minutes, TimeZoneInfo timeZone, TimeZoneOffsetResolver resolver) { return dateTime.Add(TimeSpan.FromMinutes(minutes), timeZone, resolver); }
protected override async Task <IEnumerable <ReleaseInfo> > PerformQuery(TorznabQuery query) { TimeZoneInfo.TransitionTime startTransition = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 3, 0, 0), 3, 5, DayOfWeek.Sunday); TimeZoneInfo.TransitionTime endTransition = TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, 4, 0, 0), 10, 5, DayOfWeek.Sunday); TimeSpan delta = new TimeSpan(1, 0, 0); TimeZoneInfo.AdjustmentRule adjustment = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new DateTime(1999, 10, 1), DateTime.MaxValue.Date, delta, startTransition, endTransition); TimeZoneInfo.AdjustmentRule[] adjustments = { adjustment }; TimeZoneInfo germanyTz = TimeZoneInfo.CreateCustomTimeZone("W. Europe Standard Time", new TimeSpan(1, 0, 0), "(GMT+01:00) W. Europe Standard Time", "W. Europe Standard Time", "W. Europe DST Time", adjustments); var releases = new List <ReleaseInfo>(); var searchString = query.GetQueryString(); var searchUrl = BrowseUrl; var queryCollection = new NameValueCollection(); queryCollection.Add("showsearch", "1"); queryCollection.Add("incldead", "1"); queryCollection.Add("orderby", "added"); queryCollection.Add("sort", "desc"); if (!string.IsNullOrWhiteSpace(searchString)) { queryCollection.Add("search", searchString); } foreach (var cat in MapTorznabCapsToTrackers(query)) { queryCollection.Add("c" + cat, "1"); } searchUrl += "?" + queryCollection.GetQueryString(); var response = await RequestStringWithCookies(searchUrl); var results = response.Content; try { CQ dom = results; var globalFreeleech = dom.Find("div > img[alt=\"Only Upload\"][title^=\"ONLY UPLOAD \"]").Any(); var rows = dom["table.tableinborder > tbody > tr:has(td.tableb)"]; foreach (var row in rows) { var release = new ReleaseInfo(); var qRow = row.Cq(); var qDetailsLink = qRow.Find("a[href^=details.php?id=]").First(); release.Title = qDetailsLink.Attr("title"); if (!query.MatchQueryStringAND(release.Title)) { continue; } var qCatLink = qRow.Find("a[href^=browse.php?cat=]").First(); var qDLLink = qRow.Find("a[href^=download.php?torrent=]").First(); var qSeeders = qRow.Find("span:contains(Seeder) > b:eq(0)"); var qLeechers = qRow.Find("span:contains(Seeder) > b:eq(1)"); var qDateStr = qRow.Find("td > table > tbody > tr > td:eq(7)").First(); var qSize = qRow.Find("span:contains(Volumen) > b:eq(0)").First(); var qOnlyUpload = qRow.Find("img[title=OnlyUpload]"); if (qOnlyUpload.Any()) { release.MinimumRatio = 2; release.MinimumSeedTime = 144 * 60 * 60; } else { release.MinimumRatio = 1; release.MinimumSeedTime = 72 * 60 * 60; } var catStr = qCatLink.Attr("href").Split('=')[1]; release.Category = MapTrackerCatToNewznab(catStr); release.Link = new Uri(SiteLink + qDLLink.Attr("href")); release.Comments = new Uri(SiteLink + qDetailsLink.Attr("href")); release.Guid = release.Link; var sizeStr = qSize.Text(); release.Size = ReleaseInfo.GetBytes(sizeStr); release.Seeders = ParseUtil.CoerceInt(qSeeders.Text()); release.Peers = ParseUtil.CoerceInt(qLeechers.Text()) + release.Seeders; var dateStr = qDateStr.Text().Trim().Replace('\xA0', ' '); DateTime dateGerman = DateTime.SpecifyKind(DateTime.ParseExact(dateStr, "dd.MM.yyyy HH:mm", CultureInfo.InvariantCulture), DateTimeKind.Unspecified); DateTime pubDateUtc = TimeZoneInfo.ConvertTimeToUtc(dateGerman, germanyTz); release.PublishDate = pubDateUtc.ToLocalTime(); var files = qRow.Find("a[href*=\"&filelist=1\"] ~ font ~ b").Text(); release.Files = ParseUtil.CoerceInt(files); var grabs = qRow.Find("a[href*=\"&tosnatchers=1\"] ~ font ~ b").Text(); release.Grabs = ParseUtil.CoerceInt(grabs); if (globalFreeleech) { release.DownloadVolumeFactor = 0; } else if (qRow.Find("img[alt=\"OU\"]").Length >= 1) { release.DownloadVolumeFactor = 0; } else { release.DownloadVolumeFactor = 1; } release.UploadVolumeFactor = 1; releases.Add(release); } } catch (Exception ex) { OnParseError(results, ex); } return(releases); }
public static DateTimeOffset AddSeconds(this DateTime dateTime, double seconds, TimeZoneInfo timeZone, TimeZoneOffsetResolver resolver) { return dateTime.Add(TimeSpan.FromSeconds(seconds), timeZone, resolver); }
/// <summary> /// 指定时间转换为Unix时间 /// </summary> /// <param name="time">需要转换的时间</param> /// <returns>转换后的Unix时间</returns> public static string ToUnixTime(this DateTime time) { var t = (time.Ticks - TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1, 0, 0, 0), TimeZoneInfo.Local).Ticks) / 10000000; return(t.ToString()); }
internal static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo destinationTimeZone) { // TODO: fix it for .net 2.0 return dateTime; }
internal DateTimeZone(Context ctx, TimeZoneInfo resolvedTimeZone) : this(ctx) { Debug.Assert(resolvedTimeZone != null); timezone = resolvedTimeZone; }
public static DateTimeOffset AddHours(this DateTimeOffset dateTimeOffset, double hours, TimeZoneInfo timeZone) { return dateTimeOffset.Add(TimeSpan.FromHours(hours), timeZone); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IPeriodicCanvasJobs periodicCanvasJobs) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseSwagger(); app.UseSwaggerUI(x => { x.SwaggerEndpoint("/swagger/v1/swagger.json", "My Api"); }); app.UseHangfireDashboard(); RecurringJob.AddOrUpdate("some-id", () => periodicCanvasJobs.CreateNewCanvas(), "0 0 * * *", TimeZoneInfo.FindSystemTimeZoneById("New Zealand Standard Time")); app.UseRouting(); app.UseCors(builder => { builder.WithOrigins(Configuration["AllowedOrigins"].Split(";")) .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapHub <SignalRHub>("/hub"); }); }
public static DateTimeOffset AddTicks(this DateTimeOffset dateTimeOffset, long ticks, TimeZoneInfo timeZone) { return dateTimeOffset.Add(TimeSpan.FromTicks(ticks), timeZone); }
public static DateTimeOffset Subtract(this DateTime dateTime, TimeSpan timeSpan, TimeZoneInfo timeZone, TimeZoneOffsetResolver resolver) { return dateTime.Add(timeSpan.Negate(), timeZone, resolver); }
// public static bool TryCreate(string aLine, out ProductSettlementEntry newEntry, DateTime settmentDate) { newEntry = null; string[] elements = aLine.Split(','); if (elements.Length < ProductSettlementEntry.NumberOfFields) { return(false); } newEntry = new ProductSettlementEntry(); // Load - Exchange name int elem = 0; if (!string.IsNullOrWhiteSpace(elements[elem])) { newEntry.Exchange = elements[elem].Trim(); } elem++; // Load - Product name if (!string.IsNullOrWhiteSpace(elements[elem])) { newEntry.Product = elements[elem].Trim(); } elem++; // Load - Product type if (!string.IsNullOrWhiteSpace(elements[elem])) { ProductTypes type; if (Enum.TryParse <ProductTypes>(elements[elem].Trim(), out type)) { newEntry.Type = type; } } elem++; // // Load - Timezone name // if (!string.IsNullOrWhiteSpace(elements[elem])) { TimeZoneInfo tzInfo = null; try { tzInfo = TimeZoneInfo.FindSystemTimeZoneById(elements[elem].Trim()); newEntry.TZInfo = tzInfo; } catch (Exception) { return(false); } } elem++; // Load - settlement time in local time of exchange. if (!string.IsNullOrWhiteSpace(elements[elem])) { TimeSpan time; if (TimeSpan.TryParse(elements[elem].Trim(), out time)) { //newEntry.MinuteOffset = (int)(MinutesPerHour * x); newEntry.SettleTime = time;//.Subtract(time.TimeOfDay); } else { return(false); // This is necessary! } } elem++; // Exit. return(newEntry.TryInitialize(settmentDate));; }//TryCreate()
// /// <summary> /// Method used to create a Settlement table from a file path. /// </summary> /// <param name="filePath"></param> /// <param name="newTable"></param> /// <returns>true if table is created</returns> public static bool TryCreate(string filePath, out ProductSettlementTable newTable, DateTime settlement) { newTable = null; // // Load file, remove comments. // string[] fileLines = null; try { fileLines = System.IO.File.ReadAllLines(filePath); // raw lines from file. } catch (Exception) { return(false); } List <string> cleanLines = new List <string>(); // lines cleaned of comments etc. foreach (string aLine in fileLines) { int n = aLine.IndexOf("//"); string s = aLine; if (n > -1) { s = aLine.Substring(0, n); } s = s.Trim(); if (!string.IsNullOrEmpty(s)) { cleanLines.Add(s); } } // // Create table. // newTable = new ProductSettlementTable(); foreach (string aLine in cleanLines) { ProductSettlementEntry newEntry; if (ProductSettlementEntry.TryCreate(aLine, out newEntry, settlement)) { newEntry.IgnoreCaseOfNames = newTable.IgnoreCaseOfNames; newTable.Rows.Add(newEntry); // Report StringBuilder s = new StringBuilder(); TimeZoneInfo tzLocal = TimeZoneInfo.Local; DateTime settle = DateTime.Now.Date; DateTime foreignSettle = new DateTime(settle.Year, settle.Month, settle.Day, 0, 0, 0, DateTimeKind.Unspecified); foreignSettle = foreignSettle.Add(newEntry.SettleTime); TimeZoneInfo foreignTZ = newEntry.TZInfo; try { DateTime settleLocal = TimeZoneInfo.ConvertTime(foreignSettle, foreignTZ, tzLocal); s.AppendFormat("{0} ---> Local Settlement: {1}", newEntry, settleLocal); } catch (Exception e) { s.AppendFormat("{0}", e.Message); } Console.WriteLine(s.ToString()); } } newTable.Rows.Sort(ProductSettlementEntry.CompareEntriesBySpecificity); return(true); }//TryCreate()
protected async Task <List <EventModel> > GetEventsByTime(DateTime?startDate, DateTime?startTime, DateTime?endDate, DateTime?endTime, TimeZoneInfo userTimeZone, ICalendar calendarService) { // todo: check input datetime is utc var rawEvents = new List <EventModel>(); var resultEvents = new List <EventModel>(); bool searchByStartTime = startTime != null && endDate == null && endTime == null; startDate = startDate ?? TimeConverter.ConvertUtcToUserTime(DateTime.UtcNow, userTimeZone); endDate = endDate ?? startDate ?? TimeConverter.ConvertUtcToUserTime(DateTime.UtcNow, userTimeZone); var searchStartTime = startTime == null ? new DateTime(startDate.Value.Year, startDate.Value.Month, startDate.Value.Day) : new DateTime(startDate.Value.Year, startDate.Value.Month, startDate.Value.Day, startTime.Value.Hour, startTime.Value.Minute, startTime.Value.Second); searchStartTime = TimeZoneInfo.ConvertTimeToUtc(searchStartTime, userTimeZone); var searchEndTime = endTime == null ? new DateTime(endDate.Value.Year, endDate.Value.Month, endDate.Value.Day, 23, 59, 59) : new DateTime(endDate.Value.Year, endDate.Value.Month, endDate.Value.Day, endTime.Value.Hour, endTime.Value.Minute, endTime.Value.Second); searchEndTime = TimeZoneInfo.ConvertTimeToUtc(searchEndTime, userTimeZone); if (searchByStartTime) { rawEvents = await calendarService.GetEventsByStartTime(searchStartTime); } else { rawEvents = await calendarService.GetEventsByTime(searchStartTime, searchEndTime); } foreach (var item in rawEvents) { if (item.StartTime >= searchStartTime && item.IsCancelled != true) { resultEvents.Add(item); } } return(resultEvents); }
public static DateTime ToDisplayTime(this DateTime inpTime) => TimeZoneInfo.ConvertTimeFromUtc(inpTime, cstZone);
public static DateTimeOffset Add(this DateTime dateTime, TimeSpan timeSpan, TimeZoneInfo timeZone) { return dateTime.Add(timeSpan, timeZone, TimeZoneOffsetResolvers.Default); }
protected async Task DigestCalendarLuisResult(DialogContext dc, Calendar luisResult, bool isBeginDialog) { try { var state = await Accessor.GetAsync(dc.Context); var entity = luisResult.Entities; if (entity.ordinal != null) { try { var eventList = state.SummaryEvents; var value = entity.ordinal[0]; var num = int.Parse(value.ToString()); if (eventList != null && num > 0) { var currentList = eventList.GetRange(0, Math.Min(CalendarSkillState.PageSize, eventList.Count)); if (num <= currentList.Count) { state.ReadOutEvents.Clear(); state.ReadOutEvents.Add(currentList[num - 1]); } } } catch { // ignored } } if (entity.number != null && entity.ordinal != null && entity.ordinal.Length == 0) { try { var eventList = state.SummaryEvents; var value = entity.ordinal[0]; var num = int.Parse(value.ToString()); if (eventList != null && num > 0) { var currentList = eventList.GetRange(0, Math.Min(CalendarSkillState.PageSize, eventList.Count)); if (num <= currentList.Count) { state.ReadOutEvents.Clear(); state.ReadOutEvents.Add(currentList[num - 1]); } } } catch { // ignored } } if (!isBeginDialog) { return; } if (entity.Subject != null) { state.Title = entity.Subject[0]; } if (entity.ContactName != null) { foreach (var name in entity.ContactName) { if (!state.AttendeesNameList.Contains(name)) { state.AttendeesNameList.Add(name); } } } if (entity.Duration != null) { foreach (var datetimeItem in entity.datetime) { if (datetimeItem.Type == "duration") { var culture = dc.Context.Activity.Locale ?? English; List <DateTimeResolution> result = RecognizeDateTime(entity.Duration[0], culture); if (result != null) { if (result[0].Value != null) { state.Duration = int.Parse(result[0].Value); } } break; } } } if (entity.MeetingRoom != null) { state.Location = entity.MeetingRoom[0]; } if (entity.Location != null) { state.Location = entity.Location[0]; } if (entity.StartDate != null) { var culture = dc.Context.Activity.Locale ?? English; List <DateTimeResolution> results = RecognizeDateTime(entity.StartDate[0], culture); if (results != null) { var result = results[results.Count - 1]; if (result.Value != null) { var dateTime = DateTime.Parse(result.Value); var dateTimeConvertType = result.Timex; if (dateTime != null) { bool isRelativeTime = IsRelativeTime(entity.StartDate[0], result.Value, result.Timex); state.StartDate = isRelativeTime ? TimeZoneInfo.ConvertTime(dateTime, TimeZoneInfo.Local, state.GetUserTimeZone()) : dateTime; } } } } if (entity.StartTime != null) { var culture = dc.Context.Activity.Locale ?? English; List <DateTimeResolution> result = RecognizeDateTime(entity.StartTime[0], culture); if (result != null) { if (result[0].Value != null) { var dateTime = DateTime.Parse(result[0].Value); var dateTimeConvertType = result[0].Timex; if (dateTime != null) { bool isRelativeTime = IsRelativeTime(entity.StartTime[0], result[0].Value, result[0].Timex); state.StartTime = isRelativeTime ? TimeZoneInfo.ConvertTime(dateTime, TimeZoneInfo.Local, state.GetUserTimeZone()) : dateTime; } } else { var startTime = DateTime.Parse(result[0].Start); var endTime = DateTime.Parse(result[0].End); state.StartTime = startTime; state.EndTime = endTime; } } } if (entity.EndDate != null) { var culture = dc.Context.Activity.Locale ?? English; List <DateTimeResolution> results = RecognizeDateTime(entity.EndDate[0], culture); if (results != null) { var result = results[results.Count - 1]; if (result.Value != null) { var dateTime = DateTime.Parse(result.Value); var dateTimeConvertType = result.Timex; if (dateTime != null) { bool isRelativeTime = IsRelativeTime(entity.EndDate[0], result.Value, result.Timex); state.EndDate = isRelativeTime ? TimeZoneInfo.ConvertTime(dateTime, TimeZoneInfo.Local, state.GetUserTimeZone()) : dateTime; } } } } if (entity.EndTime != null) { var culture = dc.Context.Activity.Locale ?? English; List <DateTimeResolution> result = RecognizeDateTime(entity.EndTime[0], culture); if (result != null && result[0].Value != null) { var dateTime = DateTime.Parse(result[0].Value); var dateTimeConvertType = result[0].Timex; if (dateTime != null) { bool isRelativeTime = IsRelativeTime(entity.EndTime[0], result[0].Value, result[0].Timex); state.EndTime = isRelativeTime ? TimeZoneInfo.ConvertTime(dateTime, TimeZoneInfo.Local, state.GetUserTimeZone()) : dateTime; } } } if (entity.OriginalStartDate != null) { var culture = dc.Context.Activity.Locale ?? English; List <DateTimeResolution> results = RecognizeDateTime(entity.OriginalStartDate[0], culture); if (results != null) { var result = results[results.Count - 1]; if (result.Value != null) { var dateTime = DateTime.Parse(result.Value); var dateTimeConvertType = result.Timex; if (dateTime != null) { bool isRelativeTime = IsRelativeTime(entity.OriginalStartDate[0], result.Value, result.Timex); state.OriginalStartDate = isRelativeTime ? TimeZoneInfo.ConvertTime(dateTime, TimeZoneInfo.Local, state.GetUserTimeZone()) : dateTime; } } } } if (entity.OriginalStartTime != null) { var culture = dc.Context.Activity.Locale ?? English; List <DateTimeResolution> result = RecognizeDateTime(entity.OriginalStartTime[0], culture); if (result != null) { if (result[0].Value != null) { var dateTime = DateTime.Parse(result[0].Value); var dateTimeConvertType = result[0].Timex; if (dateTime != null) { bool isRelativeTime = IsRelativeTime(entity.OriginalStartTime[0], result[0].Value, result[0].Timex); state.OriginalStartTime = isRelativeTime ? TimeZoneInfo.ConvertTime(dateTime, TimeZoneInfo.Local, state.GetUserTimeZone()) : dateTime; } } else { var startTime = DateTime.Parse(result[0].Start); var endTime = DateTime.Parse(result[0].End); state.OriginalStartTime = startTime; state.OriginalEndTime = endTime; } } } if (entity.OriginalEndDate != null) { var culture = dc.Context.Activity.Locale ?? English; List <DateTimeResolution> results = RecognizeDateTime(entity.OriginalEndDate[0], culture); if (results != null) { var result = results[results.Count - 1]; if (result.Value != null) { var dateTime = DateTime.Parse(result.Value); var dateTimeConvertType = result.Timex; if (dateTime != null) { bool isRelativeTime = IsRelativeTime(entity.OriginalEndDate[0], result.Value, result.Timex); state.OriginalEndDate = isRelativeTime ? TimeZoneInfo.ConvertTime(dateTime, TimeZoneInfo.Local, state.GetUserTimeZone()) : dateTime; } } } } if (entity.OriginalEndTime != null) { var culture = dc.Context.Activity.Locale ?? English; List <DateTimeResolution> result = RecognizeDateTime(entity.OriginalEndTime[0], culture); if (result != null && result[0].Value != null) { var dateTime = DateTime.Parse(result[0].Value); var dateTimeConvertType = result[0].Timex; if (dateTime != null) { bool isRelativeTime = IsRelativeTime(entity.OriginalEndTime[0], result[0].Value, result[0].Timex); state.OriginalEndTime = isRelativeTime ? TimeZoneInfo.ConvertTimeToUtc(dateTime, TimeZoneInfo.Local) : TimeConverter.ConvertLuisLocalToUtc(dateTime, state.GetUserTimeZone()); } } } } catch { // put log here } }
private static DateTimeOffset AddByDate(DateTime dateTime, Func<DateTime, DateTime> operation, TimeZoneInfo timeZone, TimeZoneOffsetResolver resolver) { if (dateTime.Kind != DateTimeKind.Unspecified) { dateTime = TimeZoneInfo.ConvertTime(dateTime, timeZone); } var dt = operation.Invoke(dateTime); return resolver.Invoke(dt, timeZone); }
/// <summary> /// This method ensures that all services managed by this class are initialized /// correctly taking into account specialization state transitions. /// </summary> internal void EnsureInitialized(WebHostSettings settings) { // Create a logger that we can use when the host isn't yet initialized. ILogger logger = _loggerFactory.CreateLogger(LogCategories.Startup); lock (_syncLock) { // Determine whether we should do normal or standby initialization if (!WebScriptHostManager.InStandbyMode) { // We're not in standby mode. There are two cases to consider: // 1) We _were_ in standby mode and now we're ready to specialize // 2) We're doing non-specialization normal initialization if (_activeHostManager == null && (_standbyHostManager == null || _settingsManager.ContainerReady)) { _specializationTimer?.Dispose(); _specializationTimer = null; _activeScriptHostConfig = CreateScriptHostConfiguration(settings); _activeHostManager = new WebScriptHostManager(_activeScriptHostConfig, _secretManagerFactory, _eventManager, _settingsManager, settings, _router, loggerProviderFactory: _loggerProviderFactory, loggerFactory: _loggerFactory, eventGenerator: _eventGenerator); //_activeReceiverManager = new WebHookReceiverManager(_activeHostManager.SecretManager); InitializeFileSystem(settings, _settingsManager.FileSystemIsReadOnly); if (_standbyHostManager != null) { // we're starting the one and only one // standby mode specialization logger.LogInformation(Resources.HostSpecializationTrace); // After specialization, we need to ensure that custom timezone // settings configured by the user (WEBSITE_TIME_ZONE) are honored. // DateTime caches timezone information, so we need to clear the cache. TimeZoneInfo.ClearCachedData(); } if (_standbyHostManager != null) { _standbyHostManager.Stop(); _standbyHostManager.Dispose(); } //_standbyReceiverManager?.Dispose(); _standbyScriptHostConfig = null; _standbyHostManager = null; //_standbyReceiverManager = null; } } else { // We're in standby (placeholder) mode. Initialize the standby services. if (_standbyHostManager == null) { var standbySettings = CreateStandbySettings(settings); _standbyScriptHostConfig = CreateScriptHostConfiguration(standbySettings, true); _standbyHostManager = new WebScriptHostManager(_standbyScriptHostConfig, _secretManagerFactory, _eventManager, _settingsManager, standbySettings, _router, loggerProviderFactory: _loggerProviderFactory, loggerFactory: _loggerFactory, eventGenerator: _eventGenerator); // _standbyReceiverManager = new WebHookReceiverManager(_standbyHostManager.SecretManager); InitializeFileSystem(settings, _settingsManager.FileSystemIsReadOnly); StandbyManager.Initialize(_standbyScriptHostConfig, logger); // start a background timer to identify when specialization happens // specialization usually happens via an http request (e.g. scale controller // ping) but this timer is started as well to handle cases where we // might not receive a request _specializationTimer = new Timer(OnSpecializationTimerTick, settings, 1000, 1000); } } } }
public static DateTimeOffset AddDays(this DateTime dateTime, int days, TimeZoneInfo timeZone, TimeZoneOffsetResolver resolver) { return AddByDate(dateTime, dt => dt.AddDays(days), timeZone, resolver); }
protected DateTime GetSpecialTimeZoneTime(DateTime sourceDateTime) { return(TimeZoneInfo.ConvertTimeBySystemTimeZoneId(sourceDateTime, m_TimeZone)); }
public static DateTimeOffset AddMilliseconds(this DateTime dateTime, double milliseconds, TimeZoneInfo timeZone) { return dateTime.Add(TimeSpan.FromMilliseconds(milliseconds), timeZone, TimeZoneOffsetResolvers.Default); }
public DateTime Now() { return(TimeZoneInfo.ConvertTime(DateTime.UtcNow, targetTimeZone)); }
public static DateTimeOffset AddMonths(this DateTime dateTime, int months, TimeZoneInfo timeZone) { return AddByDate(dateTime, dt => dt.AddMonths(months), timeZone, TimeZoneOffsetResolvers.Default); }
public DateTime Today() { return(TimeZoneInfo.ConvertTime(DateTime.UtcNow, targetTimeZone).Date); }
public static DateTimeOffset AddTicks(this DateTime dateTime, long ticks, TimeZoneInfo timeZone, TimeZoneOffsetResolver resolver) { return dateTime.Add(TimeSpan.FromTicks(ticks), timeZone, resolver); }
/// <summary> /// コンピューター上の現在の日時を日本時刻 (JST) で表した System.DateTime オブジェクトを取得します。 /// 下記の様に利用します /// 変換する場合(UTCであること) /// HogeDate.UtcToJapanStandardTime(); /// 現在時刻を取得する場合 /// DateTime.UtcNow.UtcToJapanStandardTime(); /// </summary> /// <returns>日本時刻 (JST) で表した現在の日付と時刻を示す System.DateTime。</returns> public static DateTime UtcToJapanStandardTime(this DateTime date) { return(TimeZoneInfo.ConvertTime(date.ToUniversalTime(), TimeZoneInfo.Utc, jstTimeZoneInfo)); }
/// <summary> /// Sets the <see cref="TimeZoneInfo"/> on the configuration. /// </summary> /// <param name="configuration">The server configuration.</param> /// <param name="timeZoneInfo">The <see cref="TimeZoneInfo"/> for the configuration.</param> /// <returns></returns> public static void SetTimeZoneInfo(this HttpConfiguration configuration, TimeZoneInfo timeZoneInfo) { if (configuration == null) { throw Error.ArgumentNull("configuration"); } if (timeZoneInfo == null) { throw Error.ArgumentNull("timeZoneInfo"); } configuration.Properties[TimeZoneInfoKey] = timeZoneInfo; TimeZoneInfoHelper.TimeZone = timeZoneInfo; }
public override void Before(LuceneTestCase testInstance) { // if verbose: print some debugging stuff about which codecs are loaded. if (LuceneTestCase.VERBOSE) { ICollection <string> codecs = Codec.AvailableCodecs(); foreach (string codec in codecs) { Console.WriteLine("Loaded codec: '" + codec + "': " + Codec.ForName(codec).GetType().Name); } ICollection <string> postingsFormats = PostingsFormat.AvailablePostingsFormats(); foreach (string postingsFormat in postingsFormats) { Console.WriteLine("Loaded postingsFormat: '" + postingsFormat + "': " + PostingsFormat.ForName(postingsFormat).GetType().Name); } } savedInfoStream = InfoStream.Default; Random random = LuceneTestCase.Random(); bool v = random.NextBoolean(); if (LuceneTestCase.INFOSTREAM) { InfoStream.Default = new ThreadNameFixingPrintStreamInfoStream(Console.Out); } else if (v) { InfoStream.Default = new NullInfoStream(); } Type targetClass = testInstance.GetType(); avoidCodecs = new HashSet <string>(); var suppressCodecsAttribute = targetClass.GetTypeInfo().GetCustomAttribute <LuceneTestCase.SuppressCodecsAttribute>(); if (suppressCodecsAttribute != null) { avoidCodecs.AddAll(suppressCodecsAttribute.Value); } // set back to default LuceneTestCase.OLD_FORMAT_IMPERSONATION_IS_ACTIVE = false; savedCodec = Codec.Default; int randomVal = random.Next(10); if ("Lucene3x".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal) || ("random".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal) && "random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT, StringComparison.Ordinal) && "random".Equals(LuceneTestCase.TEST_DOCVALUESFORMAT, StringComparison.Ordinal) && randomVal == 3 && !ShouldAvoidCodec("Lucene3x"))) // preflex-only setup { codec = Codec.ForName("Lucene3x"); Debug.Assert((codec is PreFlexRWCodec), "fix your ICodecFactory to scan Lucene.Net.Tests before Lucene.Net.TestFramework"); LuceneTestCase.OLD_FORMAT_IMPERSONATION_IS_ACTIVE = true; } else if ("Lucene40".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal) || ("random".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal) && "random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT, StringComparison.Ordinal) && randomVal == 0 && !ShouldAvoidCodec("Lucene40"))) // 4.0 setup { codec = Codec.ForName("Lucene40"); LuceneTestCase.OLD_FORMAT_IMPERSONATION_IS_ACTIVE = true; Debug.Assert((codec is Lucene40RWCodec), "fix your ICodecFactory to scan Lucene.Net.Tests before Lucene.Net.TestFramework"); Debug.Assert((PostingsFormat.ForName("Lucene40") is Lucene40RWPostingsFormat), "fix your IPostingsFormatFactory to scan Lucene.Net.Tests before Lucene.Net.TestFramework"); } else if ("Lucene41".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal) || ("random".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal) && "random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT, StringComparison.Ordinal) && "random".Equals(LuceneTestCase.TEST_DOCVALUESFORMAT, StringComparison.Ordinal) && randomVal == 1 && !ShouldAvoidCodec("Lucene41"))) { codec = Codec.ForName("Lucene41"); LuceneTestCase.OLD_FORMAT_IMPERSONATION_IS_ACTIVE = true; Debug.Assert((codec is Lucene41RWCodec), "fix your ICodecFactory to scan Lucene.Net.Tests before Lucene.Net.TestFramework"); } else if ("Lucene42".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal) || ("random".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal) && "random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT, StringComparison.Ordinal) && "random".Equals(LuceneTestCase.TEST_DOCVALUESFORMAT, StringComparison.Ordinal) && randomVal == 2 && !ShouldAvoidCodec("Lucene42"))) { codec = Codec.ForName("Lucene42"); LuceneTestCase.OLD_FORMAT_IMPERSONATION_IS_ACTIVE = true; Debug.Assert((codec is Lucene42RWCodec), "fix your ICodecFactory to scan Lucene.Net.Tests before Lucene.Net.TestFramework"); } else if ("Lucene45".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal) || ("random".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal) && "random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT, StringComparison.Ordinal) && "random".Equals(LuceneTestCase.TEST_DOCVALUESFORMAT, StringComparison.Ordinal) && randomVal == 5 && !ShouldAvoidCodec("Lucene45"))) { codec = Codec.ForName("Lucene45"); LuceneTestCase.OLD_FORMAT_IMPERSONATION_IS_ACTIVE = true; Debug.Assert((codec is Lucene45RWCodec), "fix your ICodecFactory to scan Lucene.Net.Tests before Lucene.Net.TestFramework"); } else if (("random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT, StringComparison.Ordinal) == false) || ("random".Equals(LuceneTestCase.TEST_DOCVALUESFORMAT, StringComparison.Ordinal) == false)) { // the user wired postings or DV: this is messy // refactor into RandomCodec.... PostingsFormat format; if ("random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT, StringComparison.Ordinal)) { format = PostingsFormat.ForName("Lucene41"); } else if ("MockRandom".Equals(LuceneTestCase.TEST_POSTINGSFORMAT, StringComparison.Ordinal)) { format = new MockRandomPostingsFormat(new Random(random.Next())); } else { format = PostingsFormat.ForName(LuceneTestCase.TEST_POSTINGSFORMAT); } DocValuesFormat dvFormat; if ("random".Equals(LuceneTestCase.TEST_DOCVALUESFORMAT, StringComparison.Ordinal)) { dvFormat = DocValuesFormat.ForName("Lucene45"); } else { dvFormat = DocValuesFormat.ForName(LuceneTestCase.TEST_DOCVALUESFORMAT); } codec = new Lucene46CodecAnonymousInnerClassHelper(this, format, dvFormat); } else if ("SimpleText".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal) || ("random".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal) && randomVal == 9 && LuceneTestCase.Rarely(random) && !ShouldAvoidCodec("SimpleText"))) { codec = new SimpleTextCodec(); } else if ("CheapBastard".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal) || ("random".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal) && randomVal == 8 && !ShouldAvoidCodec("CheapBastard") && !ShouldAvoidCodec("Lucene41"))) { // we also avoid this codec if Lucene41 is avoided, since thats the postings format it uses. codec = new CheapBastardCodec(); } else if ("Asserting".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal) || ("random".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal) && randomVal == 6 && !ShouldAvoidCodec("Asserting"))) { codec = new AssertingCodec(); } else if ("Compressing".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal) || ("random".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal) && randomVal == 5 && !ShouldAvoidCodec("Compressing"))) { codec = CompressingCodec.RandomInstance(random); } else if (!"random".Equals(LuceneTestCase.TEST_CODEC, StringComparison.Ordinal)) { codec = Codec.ForName(LuceneTestCase.TEST_CODEC); } else if ("random".Equals(LuceneTestCase.TEST_POSTINGSFORMAT, StringComparison.Ordinal)) { codec = new RandomCodec(random, avoidCodecs); } else { Debug.Assert(false); } Codec.Default = codec; // Initialize locale/ timezone. string testLocale = SystemProperties.GetProperty("tests.locale", "random"); string testTimeZone = SystemProperties.GetProperty("tests.timezone", "random"); // Always pick a random one for consistency (whether tests.locale was specified or not). savedLocale = CultureInfo.CurrentCulture; CultureInfo randomLocale = LuceneTestCase.RandomLocale(random); locale = testLocale.Equals("random", StringComparison.Ordinal) ? randomLocale : LuceneTestCase.LocaleForName(testLocale); #if NETSTANDARD CultureInfo.CurrentCulture = locale; #else Thread.CurrentThread.CurrentCulture = locale; #endif // TimeZone.getDefault will set user.timezone to the default timezone of the user's locale. // So store the original property value and restore it at end. restoreProperties["user.timezone"] = SystemProperties.GetProperty("user.timezone"); savedTimeZone = testInstance.TimeZone; TimeZoneInfo randomTimeZone = LuceneTestCase.RandomTimeZone(random); timeZone = testTimeZone.Equals("random", StringComparison.Ordinal) ? randomTimeZone : TimeZoneInfo.FindSystemTimeZoneById(testTimeZone); //TimeZone.Default = TimeZone; // LUCENENET NOTE: There doesn't seem to be an equivalent to this, but I don't think we need it. similarity = random.NextBoolean() ? (Similarity) new DefaultSimilarity() : new RandomSimilarityProvider(random); // Check codec restrictions once at class level. try { CheckCodecRestrictions(codec); } catch (Exception e) { Console.Error.WriteLine("NOTE: " + e.Message + " Suppressed codecs: " + Arrays.ToString(avoidCodecs.ToArray())); throw e; } }
public static DateTimeOffset Add(this DateTimeOffset dateTimeOffset, TimeSpan timeSpan, TimeZoneInfo timeZone) { var t = dateTimeOffset.Add(timeSpan); return TimeZoneInfo.ConvertTime(t, timeZone); }
public static DateTime GetLocalDateTime() { TimeZoneInfo infotime = TimeZoneInfo.FindSystemTimeZoneById("Arabian Standard Time"); return(TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, infotime)); }
public static DateTimeOffset AddDays(this DateTimeOffset dateTimeOffset, int days, TimeZoneInfo timeZone) { return AddByDate(dateTimeOffset, dt => dt.AddDays(days), timeZone, TimeZoneOffsetResolvers.Default); }
public override void Execute() { WriteLiteral("\r\n"); #line 10 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Layout = new LayoutPage(Strings.RecurringJobsPage_Title); List <RecurringJobDto> recurringJobs; int from, perPage; int.TryParse(Query("from"), out from); int.TryParse(Query("count"), out perPage); Pager pager = null; using (var connection = Storage.GetConnection()) { var storageConnection = connection as JobStorageConnection; if (storageConnection != null) { pager = new Pager(from, perPage, storageConnection.GetRecurringJobCount()); recurringJobs = storageConnection.GetRecurringJobs(pager.FromRecord, pager.FromRecord + pager.RecordsPerPage); } else { recurringJobs = connection.GetRecurringJobs(); } } #line default #line hidden WriteLiteral("\r\n<div class=\"row\">\r\n <div class=\"col-md-12\">\r\n <h1 class=\"page-header\"" + ">"); #line 38 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write(Strings.RecurringJobsPage_Title); #line default #line hidden WriteLiteral("</h1>\r\n\r\n"); #line 40 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" if (recurringJobs.Count == 0) { #line default #line hidden WriteLiteral(" <div class=\"alert alert-info\">\r\n "); #line 43 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write(Strings.RecurringJobsPage_NoJobs); #line default #line hidden WriteLiteral("\r\n </div>\r\n"); #line 45 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" } else { #line default #line hidden WriteLiteral(" <div class=\"js-jobs-list\">\r\n <div class=\"btn-toolbar b" + "tn-toolbar-top\">\r\n <button class=\"js-jobs-list-command btn bt" + "n-sm btn-primary\"\r\n data-url=\""); #line 51 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write(Url.To("/recurring/trigger")); #line default #line hidden WriteLiteral("\"\r\n data-loading-text=\""); #line 52 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write(Strings.RecurringJobsPage_Triggering); #line default #line hidden WriteLiteral("\"\r\n disabled=\"disabled\">\r\n <spa" + "n class=\"glyphicon glyphicon-play-circle\"></span>\r\n "); #line 55 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write(Strings.RecurringJobsPage_TriggerNow); #line default #line hidden WriteLiteral("\r\n </button>\r\n\r\n <button class=\"js-jobs-lis" + "t-command btn btn-sm btn-default\"\r\n data-url=\""); #line 59 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write(Url.To("/recurring/remove")); #line default #line hidden WriteLiteral("\"\r\n data-loading-text=\""); #line 60 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write(Strings.Common_Deleting); #line default #line hidden WriteLiteral("\"\r\n data-confirm=\""); #line 61 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write(Strings.Common_DeleteConfirm); #line default #line hidden WriteLiteral("\"\r\n disabled=\"disabled\">\r\n <spa" + "n class=\"glyphicon glyphicon-remove\"></span>\r\n "); #line 64 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write(Strings.Common_Delete); #line default #line hidden WriteLiteral("\r\n </button>\r\n\r\n"); #line 67 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" if (pager != null) { #line default #line hidden WriteLiteral(" "); WriteLiteral(" "); #line 69 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write(Html.PerPageSelector(pager)); #line default #line hidden WriteLiteral("\r\n"); #line 70 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" } #line default #line hidden WriteLiteral(@" </div> <div class=""table-responsive""> <table class=""table""> <thead> <tr> <th class=""min-width""> <input type=""checkbox"" class=""js-jobs-list-select-all"" /> </th> <th class=""min-width"">"); #line 80 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write(Strings.Common_Id); #line default #line hidden WriteLiteral("</th>\r\n <th class=\"min-width\">"); #line 81 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write(Strings.RecurringJobsPage_Table_Cron); #line default #line hidden WriteLiteral("</th>\r\n <th class=\"min-width\">"); #line 82 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write(Strings.RecurringJobsPage_Table_TimeZone); #line default #line hidden WriteLiteral("</th>\r\n <th>"); #line 83 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write(Strings.Common_Job); #line default #line hidden WriteLiteral("</th>\r\n <th class=\"align-right min-width\">"); #line 84 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write(Strings.RecurringJobsPage_Table_NextExecution); #line default #line hidden WriteLiteral("</th>\r\n <th class=\"align-right min-width\">"); #line 85 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write(Strings.RecurringJobsPage_Table_LastExecution); #line default #line hidden WriteLiteral("</th>\r\n <th class=\"align-right min-width\">"); #line 86 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write(Strings.Common_Created); #line default #line hidden WriteLiteral("</th>\r\n </tr>\r\n </thead>\r\n " + " <tbody>\r\n"); #line 90 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" foreach (var job in recurringJobs) { #line default #line hidden WriteLiteral(" <tr class=\"js-jobs-list-row hover\">\r\n " + " <td>\r\n <input typ" + "e=\"checkbox\" class=\"js-jobs-list-checkbox\" name=\"jobs[]\" value=\""); #line 94 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write(job.Id); #line default #line hidden WriteLiteral("\" />\r\n </td>\r\n " + " <td class=\"min-width\">"); #line 96 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write(job.Id); #line default #line hidden WriteLiteral("</td>\r\n <td class=\"min-width\">\r\n " + " "); WriteLiteral("\r\n"); #line 99 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" string cronDescription = null; #if NETFULL try { cronDescription = string.IsNullOrEmpty(job.Cron) ? null : CronExpressionDescriptor.ExpressionDescriptor.GetDescription(job.Cron); } catch (FormatException) { } #endif #line default #line hidden WriteLiteral("\r\n"); #line 112 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" if (cronDescription != null) { #line default #line hidden WriteLiteral(" <code title=\""); #line 114 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write(cronDescription); #line default #line hidden WriteLiteral("\">"); #line 114 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write(job.Cron); #line default #line hidden WriteLiteral("</code>\r\n"); #line 115 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" } else { #line default #line hidden WriteLiteral(" <code>"); #line 118 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write(job.Cron); #line default #line hidden WriteLiteral("</code>\r\n"); #line 119 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" } #line default #line hidden WriteLiteral(" </td>\r\n <t" + "d class=\"min-width\">\r\n"); #line 122 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" if (!String.IsNullOrWhiteSpace(job.TimeZoneId)) { #line default #line hidden WriteLiteral(" <span title=\""); #line 124 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write(TimeZoneInfo.FindSystemTimeZoneById(job.TimeZoneId).DisplayName); #line default #line hidden WriteLiteral("\" data-container=\"body\">"); #line 124 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write(job.TimeZoneId); #line default #line hidden WriteLiteral("</span>\r\n"); #line 125 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" } else { #line default #line hidden WriteLiteral(" "); WriteLiteral(" UTC\r\n"); #line 129 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" } #line default #line hidden WriteLiteral(" </td>\r\n <t" + "d class=\"word-break\">\r\n"); #line 132 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" if (job.Job != null) { #line default #line hidden WriteLiteral(" "); WriteLiteral(" "); #line 134 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write(Html.JobName(job.Job)); #line default #line hidden WriteLiteral("\r\n"); #line 135 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" } else { #line default #line hidden WriteLiteral(" <em>"); #line 138 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write(job.LoadException.InnerException.Message); #line default #line hidden WriteLiteral("</em>\r\n"); #line 139 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" } #line default #line hidden WriteLiteral(" </td>\r\n <t" + "d class=\"align-right min-width\">\r\n"); #line 142 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" if (job.NextExecution != null) { #line default #line hidden #line 144 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write(Html.RelativeTime(job.NextExecution.Value)); #line default #line hidden #line 144 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" } else { #line default #line hidden WriteLiteral(" <em>"); #line 148 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write(Strings.Common_NotAvailable); #line default #line hidden WriteLiteral("</em>\r\n"); #line 149 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" } #line default #line hidden WriteLiteral(" </td>\r\n <t" + "d class=\"align-right min-width\">\r\n"); #line 152 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" if (job.LastExecution != null) { if (!String.IsNullOrEmpty(job.LastJobId)) { #line default #line hidden WriteLiteral(" <a href=\""); #line 156 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write(Url.JobDetails(job.LastJobId)); #line default #line hidden WriteLiteral("\">\r\n <span class=\"label label-" + "default label-hover\" style=\""); #line 157 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write($"background-color: {JobHistoryRenderer.GetForegroundStateColor(job.LastJobState ?? EnqueuedState.StateName)};"); #line default #line hidden WriteLiteral("\">\r\n "); #line 158 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write(Html.RelativeTime(job.LastExecution.Value)); #line default #line hidden WriteLiteral("\r\n </span>\r\n " + " </a>\r\n"); #line 161 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" } else { #line default #line hidden WriteLiteral(" <em>\r\n " + " "); #line 165 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write(Strings.RecurringJobsPage_Canceled); #line default #line hidden WriteLiteral(" "); #line 165 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write(Html.RelativeTime(job.LastExecution.Value)); #line default #line hidden WriteLiteral("\r\n </em>\r\n"); #line 167 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" } } else { #line default #line hidden WriteLiteral(" <em>"); #line 171 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write(Strings.Common_NotAvailable); #line default #line hidden WriteLiteral("</em>\r\n"); #line 172 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" } #line default #line hidden WriteLiteral(" </td>\r\n <t" + "d class=\"align-right min-width\">\r\n"); #line 175 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" if (job.CreatedAt != null) { #line default #line hidden #line 177 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write(Html.RelativeTime(job.CreatedAt.Value)); #line default #line hidden #line 177 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" } else { #line default #line hidden WriteLiteral(" <em>N/A</em>\r\n"); #line 182 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" } #line default #line hidden WriteLiteral(" </td>\r\n </tr>\r" + "\n"); #line 185 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" } #line default #line hidden WriteLiteral(" </tbody>\r\n </table>\r\n <" + "/div>\r\n\r\n"); #line 190 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" if (pager != null) { #line default #line hidden WriteLiteral(" "); WriteLiteral(" "); #line 192 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" Write(Html.Paginator(pager)); #line default #line hidden WriteLiteral("\r\n"); #line 193 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" } #line default #line hidden WriteLiteral(" </div>\r\n"); #line 195 "..\..\Dashboard\Pages\RecurringJobsPage.cshtml" } #line default #line hidden WriteLiteral(" </div>\r\n</div> "); }
public static DateTimeOffset AddMinutes(this DateTimeOffset dateTimeOffset, double minutes, TimeZoneInfo timeZone) { return dateTimeOffset.Add(TimeSpan.FromMinutes(minutes), timeZone); }
public static DateTime ConvertTimeOffSetFromUtc(DateTime dateValue, string timeZoneTo) { string timeZoneName = Convert.ToString(timeZoneTo).Trim(); TimeZoneInfo timeZoneFound = String.IsNullOrEmpty(timeZoneName) ? TimeZoneInfo.Local : (TimeZoneInfo.FindSystemTimeZoneById(timeZoneName) ?? TimeZoneInfo.Local); return(ConvertTimeOffSetFromUtc(dateValue, timeZoneFound)); }
public static DateTimeOffset AddSeconds(this DateTimeOffset dateTimeOffset, double seconds, TimeZoneInfo timeZone) { return dateTimeOffset.Add(TimeSpan.FromSeconds(seconds), timeZone); }
public static DateTime ConvertTimeOffSetFromUtc(DateTime dateValue, TimeZoneInfo timeZoneTo) { var accessFromOff = new DateTimeOffset(dateValue, TimeSpan.Zero); return(TimeZoneInfo.ConvertTime(accessFromOff.UtcDateTime, TimeZoneInfo.Utc, timeZoneTo)); }
public static DateTimeOffset AddYears(this DateTimeOffset dateTimeOffset, int years, TimeZoneInfo timeZone, TimeZoneOffsetResolver resolver) { return AddByDate(dateTimeOffset, dt => dt.AddYears(years), timeZone, resolver); }
public static IEnumerable <dynamic> ApplyTimeZoneToModel(IEnumerable <dynamic> model) { var applyTimeZoneToModel = model as IList <dynamic> ?? model.ToList(); foreach (var item in applyTimeZoneToModel) { bool isTemporal1 = item.isTemporal != null && item.isTemporal; bool isTemporal2 = item.IsTemporal != null && item.IsTemporal; bool isTemporal3 = item.istemporal != null && item.istemporal; bool hasLocationTimeZone = item.locationTimeZone != null; if ((isTemporal1 || isTemporal2 || isTemporal3) && hasLocationTimeZone) { string timeZoneName = Convert.ToString(item.locationTimeZone).Trim(); var itemTimeZone = String.IsNullOrEmpty(timeZoneName) ? TimeZoneInfo.Local : (TimeZoneInfo.FindSystemTimeZoneById(timeZoneName) ?? TimeZoneInfo.Local); // START DATE if (item.StartDate != null && !(item.StartDate is DBNull)) { var startDateOff = new DateTimeOffset(item.StartDate, TimeSpan.Zero); item.StartDate = (Object)TimeZoneInfo.ConvertTime(startDateOff.UtcDateTime, TimeZoneInfo.Utc, itemTimeZone); } else if (item.accessFrom != null && !(item.accessFrom is DBNull)) { var accessFromOff = new DateTimeOffset(item.accessFrom, TimeSpan.Zero); item.accessFrom = (Object)TimeZoneInfo.ConvertTime(accessFromOff.UtcDateTime, TimeZoneInfo.Utc, itemTimeZone); } // END DATE if (item.EndDate != null && !(item.EndDate is DBNull)) { var endDateOff = new DateTimeOffset(item.EndDate, TimeSpan.Zero); item.EndDate = (Object)TimeZoneInfo.ConvertTime(endDateOff.UtcDateTime, TimeZoneInfo.Utc, itemTimeZone); } else if (item.accessTo != null && !(item.accessTo is DBNull)) { var accessToOff = new DateTimeOffset(item.accessTo, TimeSpan.Zero); item.accessTo = (Object)TimeZoneInfo.ConvertTime(accessToOff.UtcDateTime, TimeZoneInfo.Utc, itemTimeZone); } } } return(applyTimeZoneToModel); }
public static DateTimeOffset Subtract(this DateTimeOffset dateTimeOffset, TimeSpan timeSpan, TimeZoneInfo timeZone) { return dateTimeOffset.Add(timeSpan.Negate(), timeZone); }
public static CryptsyOrder ReadFromJObject(JObject o, Int64 marketId = -1, CryptsyOrderType orderType = CryptsyOrderType.Na) { if (o == null) { return(null); } var order = new CryptsyOrder { Price = o.Value <decimal>("price"), Quantity = o.Value <decimal>("quantity"), Total = o.Value <decimal>("total"), OriginalQuantity = o.Value <decimal?>("orig_quantity") ?? -1, MarketId = o.Value <Int64?>("marketid") ?? marketId, //If ordertype is present, use it, if not: use the ordertype passed to the method OrderType = o.Value <string>("ordertype") == null ? orderType : (o.Value <string>("ordertype").ToLower() == "buy" ? CryptsyOrderType.Buy : CryptsyOrderType.Sell), CreatedUtc = o.Value <DateTime?>("created") }; if (order.CreatedUtc != null) { order.CreatedUtc = TimeZoneInfo.ConvertTime((DateTime)order.CreatedUtc, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"), TimeZoneInfo.Utc); //Convert to UTC } return(order); }
/// <summary> /// Converts a DateTimeOffset into a DateTime using the specified time zone. /// </summary> /// <param name = "dateTimeUtc">The base DateTimeOffset.</param> /// <param name = "localTimeZone">The time zone to be used for conversion.</param> /// <returns>The converted DateTime</returns> public static DateTime ToLocalDateTime(this DateTimeOffset dateTimeUtc, TimeZoneInfo localTimeZone) { return TimeZoneInfo.ConvertTime(dateTimeUtc, (localTimeZone ?? TimeZoneInfo.Local)).DateTime; }
public EventWrapper(IEvent baseEvent, Guid userId, TimeZoneInfo timeZone) { _timeZone = timeZone; _baseEvent = baseEvent; this.UserId = userId; }