protected void tmr_SecsTrigger_Tick(object sender, EventArgs e) { try { if (0 > DateTime.Compare(TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, IST), DateTime.Parse(Session["TimeOut"].ToString()))) { lbl_secs.Text = "Refreshing again in " + ((Int32)DateTime.Parse(Session["TimeOut"].ToString()).Subtract(TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, IST)).TotalSeconds).ToString() + "s"; } else { Session["TimeOut"] = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, IST).AddSeconds(19).ToString(); refreshData(); } } catch { Response.Redirect(Request.RawUrl); } }
public async Task <IActionResult> TopNRoomsAsync([FromBody] ScheduleSearch search) { if (search == null) { return(this.BadRequest(new { message = "Search details parameter is null." })); } try { var claims = this.GetUserClaims(); var token = await this.tokenHelper.GetUserTokenAsync(claims.FromId).ConfigureAwait(false); if (string.IsNullOrEmpty(token)) { this.telemetryClient.TrackTrace($"Azure Active Directory access token for user {claims.UserObjectIdentifer} is empty. Cannot search rooms."); return(this.StatusCode( (int)HttpStatusCode.Unauthorized, new Error { StatusCode = SignInErrorCode, ErrorMessage = "Azure Active Directory access token for user is found empty.", })); } var allRooms = await this.roomCollectionStorageProvider.GetNRoomsAsync(InitialRoomCount).ConfigureAwait(false); if (allRooms == null) { return(this.StatusCode(StatusCodes.Status500InternalServerError, "Unable to fetch rooms from storage")); } if (search.IsScheduleRequired) { var conversionResult = DateTime.TryParse(search.Time, out DateTime localTime); var startUTCDateTime = localTime.AddMinutes(Constants.DurationGapFromNow.Minutes); var startDateTime = TimeZoneInfo.ConvertTimeFromUtc(startUTCDateTime, TimeZoneInfo.FindSystemTimeZoneById(TZConvert.IanaToWindows(search.TimeZone))); search.Time = startDateTime.ToString("yyyy-MM-dd HH:mm:ss"); var rooms = allRooms.Select(room => room.RowKey).ToList(); var scheduleResponse = await this.meetingHelper.GetRoomScheduleAsync(search, rooms, token).ConfigureAwait(false); if (scheduleResponse.ErrorResponse != null) { // Graph API returned error message. return(this.StatusCode((int)scheduleResponse.StatusCode, scheduleResponse.ErrorResponse.Error.ErrorMessage)); } var searchResults = allRooms.Select(searchResult => new SearchResult(searchResult) { Label = searchResult.RoomName, Value = searchResult.RowKey, Sublabel = searchResult.BuildingName + " | C-" + (string.IsNullOrEmpty(searchResult.Capacity) ? "-" : searchResult.Capacity) + " | F-" + (string.IsNullOrEmpty(searchResult.FloorNumber) ? "-" : searchResult.FloorNumber) + " | D-" + (string.IsNullOrEmpty(searchResult.DisplayDevice) ? "-" : searchResult.DisplayDevice), Status = scheduleResponse?.Schedules.Where(schedule => schedule.ScheduleId == searchResult.RowKey).FirstOrDefault()?.ScheduleItems == null || scheduleResponse?.Schedules.Where(schedule => schedule.ScheduleId == searchResult.RowKey).FirstOrDefault()?.ScheduleItems?.Count > 0 ? Strings.Unavailable : Strings.Available, }).ToList(); return(this.Ok(searchResults)); } else { var searchResults = allRooms.Select(searchResult => new SearchResult(searchResult) { Label = searchResult.RoomName, Value = searchResult.RowKey, Sublabel = searchResult.BuildingName + " | C-" + (string.IsNullOrEmpty(searchResult.Capacity) ? "-" : searchResult.Capacity) + " | F-" + (string.IsNullOrEmpty(searchResult.FloorNumber) ? "-" : searchResult.FloorNumber) + " | D-" + (string.IsNullOrEmpty(searchResult.DisplayDevice) ? "-" : searchResult.DisplayDevice), }).ToList(); return(this.Ok(searchResults)); } } catch (Exception ex) { this.telemetryClient.TrackException(ex); return(this.StatusCode(StatusCodes.Status500InternalServerError, ex.Message)); } }
/// <summary> /// Converts a Coordinated Universal Time (UTC) to the time in a specified time zone. /// </summary> /// <param name="dateTime">The Coordinated Universal Time (UTC).</param> /// <param name="destinationTimeZone">The time zone to convert to.</param> /// <returns> /// The date and time in the destination time zone. Its property is if is ; otherwise, its property is . /// </returns> public static DateTime ConvertTimeFromUtc(this DateTime dateTime, TimeZoneInfo destinationTimeZone) { return(TimeZoneInfo.ConvertTimeFromUtc(dateTime, destinationTimeZone)); }
public static string ToTimeZone(this DateTime dateTime, string format, string nameOfTimeZone = TimeZoneAthens) { var tst = TZConvert.GetTimeZoneInfo(nameOfTimeZone); return(TimeZoneInfo.ConvertTimeFromUtc(dateTime, tst).ToString(format)); }
internal object ConvertFromNativeLayer() { if (this.isTimestamp) { // "Now" value defined in line 1934, page 53 of DSP0004, version 2.6.0 if ((this.timestamp.year == 0) && (this.timestamp.month == 1) && (this.timestamp.day == 1) && (this.timestamp.hour == 0) && (this.timestamp.minute == 0) && (this.timestamp.second == 0) && (this.timestamp.microseconds == 0) && (this.timestamp.utc == 720)) { return(DateTime.Now); } // "Infinite past" value defined in line 1935, page 54 of DSP0004, version 2.6.0 else if ((this.timestamp.year == 0) && (this.timestamp.month == 1) && (this.timestamp.day == 1) && (this.timestamp.hour == 0) && (this.timestamp.minute == 0) && (this.timestamp.second == 0) && (this.timestamp.microseconds == 999999) && (this.timestamp.utc == 720)) { return(DateTime.MinValue); } // "Infinite future" value defined in line 1936, page 54 of DSP0004, version 2.6.0 else if ((this.timestamp.year == 9999) && (this.timestamp.month == 12) && (this.timestamp.day == 31) && (this.timestamp.hour == 11) && (this.timestamp.minute == 59) && (this.timestamp.second == 59) && (this.timestamp.microseconds == 999999) && (this.timestamp.utc == (-720))) { return(DateTime.MaxValue); } else { #if !_CORECLR DateTime managedUtcDateTime = new DateTime( (int)this.timestamp.year, (int)this.timestamp.month, (int)this.timestamp.day, (int)this.timestamp.hour, (int)this.timestamp.minute, (int)this.timestamp.second, (int)this.timestamp.microseconds / 1000, CultureInfo.InvariantCulture.Calendar, DateTimeKind.Utc); #else Calendar myCalendar = CultureInfo.InvariantCulture.Calendar; DateTime managedDateTime = myCalendar.ToDateTime( (int)this.timestamp.year, (int)this.timestamp.month, (int)this.timestamp.day, (int)this.timestamp.hour, (int)this.timestamp.minute, (int)this.timestamp.second, (int)this.timestamp.microseconds / 1000); DateTime managedUtcDateTime = DateTime.SpecifyKind(managedDateTime, DateTimeKind.Utc); #endif long microsecondsUnaccounted = this.timestamp.microseconds % 1000; managedUtcDateTime = managedUtcDateTime.AddTicks(microsecondsUnaccounted * 10); // since 1 microsecond == 10 ticks managedUtcDateTime = managedUtcDateTime.AddMinutes(-(this.timestamp.utc)); #if !_CORECLR DateTime managedLocalDateTime = TimeZoneInfo.ConvertTimeFromUtc(managedUtcDateTime, TimeZoneInfo.Local); #else // // TODO: USE THIS FOR BOTH CORECLR AND FULLOS // DateTime managedLocalDateTime = TimeZoneInfo.ConvertTime(managedUtcDateTime, TimeZoneInfo.Local); #endif return(managedLocalDateTime); } } else { if (TimeSpan.MaxValue.TotalDays < this.interval.days) { return(TimeSpan.MaxValue); } try { TimeSpan managedTimeSpan = new TimeSpan( (int)this.interval.days, (int)this.interval.hours, (int)this.interval.minutes, (int)this.interval.seconds, (int)this.interval.microseconds / 1000); long microsecondsUnaccounted = this.interval.microseconds % 1000; TimeSpan ticksUnaccountedTimeSpan = new TimeSpan(microsecondsUnaccounted * 10); // since 1 microsecond == 10 ticks return(managedTimeSpan.Add(ticksUnaccountedTimeSpan)); } catch (ArgumentOutOfRangeException) { return(TimeSpan.MaxValue); } } }
// 通知出力処理 private void NotificationWrite(Notification item) { string header = string.Empty; string viewName = item.Account.DisplayName.Replace("\n", "").Replace("\r", ""); viewName = viewName + "@" + item.Account.AccountName; int i = 0; long id = 0; string outputText = string.Empty; string outputString = string.Empty; string linkText = string.Empty; bool flg = true; TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time"); DateTime outTime = TimeZoneInfo.ConvertTimeFromUtc(item.CreatedAt, tzi); linkText = item.Account.ProfileUrl + "&" + item.Account.AvatarUrl + Environment.NewLine; switch (item.Type.ToLower()) { case DefaultValues.MSTDN_FAV: if (!Properties.Settings.Default.NoticeFav) { return; } header = viewName + "がお気に入りに登録 " + outTime + Environment.NewLine; break; case DefaultValues.MSTDN_BOOST: if (!Properties.Settings.Default.NoticeBoost) { return; } header = viewName + "がブースト " + outTime + Environment.NewLine; break; case DefaultValues.MSTDN_MENTION: if (!Properties.Settings.Default.NoticeMention) { return; } header = viewName + "からのメンション(" + GetVisibility(item.Status.Visibility.ToString()) + ") " + outTime + Environment.NewLine; // 返信の場合は元トゥートのURLをつける if (item.Status.InReplyToId != null) { linkText += "https://" + hostName + "/web/statuses/" + item.Status.InReplyToId; } id = item.Status.Id; break; case DefaultValues.MSTDN_FOLLOW: if (!Properties.Settings.Default.NoticeFollow) { return; } outputText = viewName + "がフォローしてきた " + outTime + Environment.NewLine; flg = false; break; } // 編集 if (flg) { // 成形 outputText = header + Molding(item.Status, out outputString, ref linkText); // 出力 i = WriteConsole(outputText, id); // リンク用処理 int start = 0; while (true) { var reg = new Regex(@"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=@]*)?"); var match = reg.Match(outputString, start); if (match.Success == true) { linkText += match.Value.ToString() + Environment.NewLine; start = match.Index + match.Length; } else { break; } } } else { // 出力 i = WriteConsole(outputText, id); } TimeLineView.Rows[i].Cells[0].ToolTipText = linkText; TimeLineView.Rows[i].Cells[0].Style.ForeColor = Properties.Settings.Default.NoticeColor; }
public static DateTime GetIndianDateTime(this DateTime datetime) { TimeZoneInfo INDIAN_ZONE = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time"); return(TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, INDIAN_ZONE)); }
//public ActionResult Edit([Bind(Prefix = "SaleOrder", Include = "BillAmount,Balance,BillPaid,Discount")] SO sO, [Bind(Prefix = "SaleOrderDetail", Include = "ProductId,Quantity")] List<SOD> sOD) public ActionResult Edit(SaleOrderViewModel saleOrderViewModel1) { SO newSO = saleOrderViewModel1.SaleOrder; List <SOD> newSODs = saleOrderViewModel1.SaleOrderDetail; if (ModelState.IsValid) { newSO.Id = Encryption.Decrypt(saleOrderViewModel1.SaleOrder.Id); // SO sO = db.SOes.Where(x => x.Id == newSO.Id).FirstOrDefault(); sO.Date = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("Pakistan Standard Time")); // sO.SaleReturn = false; // sO.BillAmount = newSO.BillAmount; // sO.Discount = newSO.Discount; // sO.Remarks = newSO.Remarks; // sO.BillPaid = newSO.BillPaid; // sO.Balance = newSO.Balance; // //sO.SOSerial = newSO.SOSerial;//should be unchanged /////////////////////////////////////////// //Customer cust = db.Customers.FirstOrDefault(x => x.Id == newSO.CustomerId); Customer customer = db.Customers.Where(x => x.Id == newSO.CustomerId).FirstOrDefault(); if (customer == null) {//its means new customer(not in db) //sO.CustomerId = 10; //int maxId = db.Customers.Max(p => p.Id); customer = saleOrderViewModel1.Customer; int maxId = db.Customers.DefaultIfEmpty().Max(p => p == null ? 0 : p.Id); maxId += 1; customer.Id = maxId; //customer.Balance = newSO.Balance; db.Customers.Add(customer); } else { db.Entry(customer).State = EntityState.Modified; } if (sO.CustomerId != newSO.CustomerId) {//some other db customer //first revert the previous customer balance Customer oldCustomer = db.Customers.Where(x => x.Id == sO.CustomerId).FirstOrDefault(); oldCustomer.Balance = db.SOes.Where(x => x.Id == sO.Id).FirstOrDefault().PrevBalance; db.Entry(oldCustomer).State = EntityState.Modified; } sO.PrevBalance = newSO.PrevBalance;// // assign balance of this customer //Customer customer = db.Customers.Where(x => x.Id == newSO.CustomerId).FirstOrDefault(); customer.Balance = newSO.Balance; //assign customer and customerId in SO sO.CustomerId = newSO.CustomerId; sO.Customer = customer; ///////////////////////////////////////////////////////////////////////////// List <SOD> oldSODs = db.SODs.Where(x => x.SOId == newSO.Id).ToList(); //handling old prodcts quantity. add old quantites back to the stock, then in next loop product quantity will be minus. this is simple and stateforward. foreach (SOD sod in oldSODs) { Product product = db.Products.FirstOrDefault(x => x.Id == sod.ProductId); if (sod.SaleType == false)//sale { product.Stock += sod.Quantity; } else//return { product.Stock -= sod.Quantity; } db.Entry(product).State = EntityState.Modified; } db.SODs.RemoveRange(oldSODs); ////////////////////////////////////////////////////////////////////////////// sO.SaleOrderAmount = 0; sO.SaleReturnAmount = 0; sO.SaleOrderQty = 0; sO.SaleReturnQty = 0; sO.Profit = 0; int sno = 0; if (newSODs != null) { foreach (SOD sod in newSODs) { sno += 1; sod.SODId = sno; sod.SO = sO; sod.SOId = sO.Id; Product product = db.Products.FirstOrDefault(x => x.Id == sod.ProductId); //sod.salePrice is now from view //sod.SalePrice = product.SalePrice; sod.PurchasePrice = product.PurchasePrice; if (sod.Quantity == null) { sod.Quantity = 0; } if (sod.SaleType == true)//return { product.Stock += sod.Quantity; sO.SaleReturnAmount += (decimal)(sod.Quantity * sod.SalePrice); sO.SaleReturnQty += (int)sod.Quantity; sO.Profit -= (sod.Quantity * sod.SalePrice) - (decimal)(sod.Quantity * product.PurchasePrice); //- (decimal)(sO.Discount); } else//sale { product.Stock -= sod.Quantity; sO.SaleOrderAmount += (decimal)(sod.Quantity * sod.SalePrice); sO.SaleOrderQty += (int)sod.Quantity; sO.Profit += (sod.Quantity * sod.SalePrice) - (decimal)(sod.Quantity * product.PurchasePrice); //- (decimal)(sO.Discount); } } sO.Profit -= (decimal)sO.Discount; db.Entry(sO).State = EntityState.Modified; db.Entry(sO).Property(x => x.SOSerial).IsModified = false; db.SODs.AddRange(newSODs); } db.SaveChanges(); return(RedirectToAction("Index")); } //ViewBag.CustomerId = new SelectList(db.Customers, "Id", "Name", sO.CustomerId); //return View(sO); SaleOrderViewModel saleOrderViewModel = new SaleOrderViewModel(); saleOrderViewModel.Products = db.Products; return(View(saleOrderViewModel)); //return View(); }
public DateTime Create() { return(TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, _timezone)); }
private void TextFillByConsultant(DataTable dt) { CultureInfo ci = new CultureInfo(CultureInfo.CurrentCulture.TwoLetterISOLanguageName); DataAccess da = new DataAccess(); reports.Text = rm.GetString("schedule", ci) + "\r\n\r\n"; string[] consultants = GetUsers(); foreach (string name in consultants) { reports.Text = reports.Text + name + "\r\n"; string startDate = ""; string endDate = ""; foreach (DataRow row in dt.Rows) { if (name == row["userName"].ToString()) { startDate = row["start"].ToString(); endDate = row["end"].ToString(); reports.Text = reports.Text + "\tStart:\t" + TimeZoneInfo.ConvertTimeFromUtc(Convert.ToDateTime(startDate), TimeZoneInfo.Local) + "\tEnd:\t" + TimeZoneInfo.ConvertTimeFromUtc(Convert.ToDateTime(endDate), TimeZoneInfo.Local) + "\r\n\r"; reports.Select(0, 0); } } } ci.ClearCachedData(); }
public ActionResult Create([Bind(Prefix = "Customer", Include = "Name,Address")] Customer Customer, [Bind(Prefix = "SaleOrder", Include = "BillAmount,Balance,PrevBalance,BillPaid,Discount,CustomerId,Remarks")] SO sO, [Bind(Prefix = "SaleOrderDetail", Include = "ProductId,SalePrice,Quantity,SaleType")] List <SOD> sOD, FormCollection collection) { string SOId = string.Empty; //SO sO = new SO(); if (ModelState.IsValid) { Customer cust = db.Customers.FirstOrDefault(x => x.Id == sO.CustomerId); if (cust == null) {//its means new customer //sO.CustomerId = 10; //int maxId = db.Customers.Max(p => p.Id); int maxId = db.Customers.DefaultIfEmpty().Max(p => p == null ? 0 : p.Id); maxId += 1; Customer.Id = maxId; Customer.Balance = sO.Balance; db.Customers.Add(Customer); //db.SaveChanges(); } else {//its means old customer. old customer balance should be updated. //Customer.Id = (int)sO.CustomerId; cust.Balance = sO.Balance; db.Entry(cust).State = EntityState.Modified; //db.SaveChanges(); //Payment payment = new Payment(); //payment = db.Payments.Find(orderId); //payment.Status = true; //db.Entry(payment).State = EntityState.Modified; //db.SaveChanges(); } //////////////////////////////////////// //int maxId = db.SOes.Max(p => p.Auto); int maxId1 = (int)db.SOes.DefaultIfEmpty().Max(p => p == null ? 0 : p.SOSerial); maxId1 += 1; sO.SOSerial = maxId1; //if (LicenseExpired(maxId1) == true) { throw null; } //sO.Date = DateTime.Now; sO.Date = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("Pakistan Standard Time")); //sO.SaleReturn = false; sO.Id = System.Guid.NewGuid().ToString().ToUpper(); sO.SaleOrderAmount = 0; sO.SaleReturnAmount = 0; sO.SaleOrderQty = 0; sO.SaleReturnQty = 0; sO.Profit = 0; db.SOes.Add(sO); //db.SaveChanges(); int sno = 0; decimal totalPurchaseAmount = 0; //sOD.RemoveAll(so => so.ProductId == null); if (sOD != null) { foreach (SOD sod in sOD) { sno += 1; sod.SODId = sno; sod.SO = sO; sod.SOId = sO.Id; Product product = db.Products.FirstOrDefault(x => x.Id == sod.ProductId); //sod.Sale Price in now from view //sod.SalePrice = product.SalePrice; sod.PurchasePrice = product.PurchasePrice; if (sod.Quantity == null) { sod.Quantity = 0; } if (sod.SaleType == true)//return { product.Stock += sod.Quantity; sO.SaleReturnAmount += (decimal)(sod.Quantity * sod.SalePrice); sO.SaleReturnQty += (int)sod.Quantity; sO.Profit -= (sod.Quantity * sod.SalePrice) - (decimal)(sod.Quantity * product.PurchasePrice); //- (decimal)(sO.Discount); } else//sale { product.Stock -= sod.Quantity; sO.SaleOrderAmount += (decimal)(sod.Quantity * sod.SalePrice); sO.SaleOrderQty += (int)sod.Quantity; sO.Profit += (sod.Quantity * sod.SalePrice) - (decimal)(sod.Quantity * product.PurchasePrice); //- (decimal)(sO.Discount); } } sO.Profit -= (decimal)sO.Discount; db.SODs.AddRange(sOD); } /////////////////////add values to payment table int maxPaymentId = db.Payments.DefaultIfEmpty().Max(p => p == null ? 0 : p.Id); maxPaymentId += 1; Payment payment = new Payment(); payment.PaymentAmount = (decimal)sO.BillPaid; payment.Id = maxPaymentId; payment.SOId = sO.Id; payment.PaymentMethod = collection.Get("SaleOrder.PaymentMethod");//"Cash"; //cash//other payment.Remarks = collection.Get("SaleOrder.PaymentRemarks"); payment.ReceivedDate = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("Pakistan Standard Time")); db.Payments.Add(payment); ////////////////////// db.SaveChanges(); //SqlParameter param1 = new SqlParameter("@SaleOrderID", sO.Id); ////var result = db.Database.ExecuteSqlCommand("spSOReceipt @SaleOrderID", param1); //var result = db.Database.SqlQuery<Object>("spSOReceipt @SaleOrderID", param1); //var cr = new ReportDocument(); //cr.Load(@"E:\PROJECTS\MYBUSINESS - v.4.6\MYBUSINESS\Reports\SOReceipt.rpt"); //cr.DataDefinition.RecordSelectionFormula = "{SaleOrderID} = '" + sO.Id + "'"; //cr.PrintToPrinter(1, true, 0, 0); ////////////////////////finalized //string pathh = HttpRuntime.AppDomainAppPath; //ReportDocument reportDocument = new ReportDocument(); //reportDocument.Load(pathh + @"Reports\SOReceipt.rpt"); //reportDocument.SetParameterValue("@SaleOrderID", sO.Id); //System.Drawing.Printing.PrinterSettings printerSettings = new System.Drawing.Printing.PrinterSettings(); ////printerSettings.PrinterName = PrinterName; //reportDocument.PrintToPrinter(printerSettings, new PageSettings(), false); ///////////////////////////////////// SOId = string.Join("-", ASCIIEncoding.ASCII.GetBytes(Encryption.Encrypt(sO.Id))); //RedirectToAction("Create", PrintSO3(SOId)); //return RedirectToAction("Create"); } return(PrintSO3(SOId)); //SaleOrderViewModel saleOrderViewModel = new SaleOrderViewModel(); //saleOrderViewModel.Customers = db.Customers; //saleOrderViewModel.Products = db.Products; //return View(saleOrderViewModel); }
public static DateTime UtcToLocal(this DateTime UtcDateTime, string TimezoneName) { return (TimeZoneInfo.ConvertTimeFromUtc(UtcDateTime, TimeZoneInfo.GetSystemTimeZones().Where(tz => TimezoneName.Equals(tz.StandardName)).Single())); }
public static DateTime ConvertTimeToLocal(this DateTime dateTime) { TimeZoneInfo zaTimeZone = TimeZoneInfo.FindSystemTimeZoneById(zaTimeZoneIdentifier); return(TimeZoneInfo.ConvertTimeFromUtc(dateTime, zaTimeZone)); }
public static DateTime GetCurrentTime(TimeZoneInfo timeZone) { timeZone.EnsureNotNull(nameof(timeZone)); return(TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, timeZone)); }
private int HoursOffset(DateTime dateTime, TimeZoneInfo timeZone) { return(Convert.ToInt32((TimeZoneInfo.ConvertTimeFromUtc(dateTime, timeZone) - dateTime).TotalHours)); }
//------------------------------------------------------------------------------------------------------------------------- /// <summary> /// Converts the supplied UTC DateTime value to a Mountain Standard DateTime. /// </summary> /// <param name="Value"></param> /// <returns></returns> public static DateTime ToMountainStandard(this DateTime Value) { return(TimeZoneInfo.ConvertTimeFromUtc(Value, TimeZoneInfo.FindSystemTimeZoneById("Mountain Standard Time"))); }
private void IncreaseBlogArchive(BlogPostPart blogPostPart) { _blogArchiveRepository.Flush(); var commonPart = blogPostPart.As <ICommonPart>(); if (commonPart == null || !commonPart.CreatedUtc.HasValue) { return; } // get the time zone for the current request var timeZone = _workContextAccessor.GetContext().CurrentTimeZone; var previousCreatedUtc = _previousCreatedUtc.ContainsKey(blogPostPart.Id) ? _previousCreatedUtc[blogPostPart.Id] : DateTime.MinValue; previousCreatedUtc = TimeZoneInfo.ConvertTimeFromUtc(previousCreatedUtc, timeZone); var previousMonth = previousCreatedUtc.Month; var previousYear = previousCreatedUtc.Year; var newCreatedUtc = commonPart.CreatedUtc; newCreatedUtc = TimeZoneInfo.ConvertTimeFromUtc(newCreatedUtc.Value, timeZone); var newMonth = newCreatedUtc.Value.Month; var newYear = newCreatedUtc.Value.Year; // if archives are the same there is nothing to do if (previousMonth == newMonth && previousYear == newYear) { return; } // decrement previous archive record var previousArchiveRecord = _blogArchiveRepository .Table .FirstOrDefault(x => x.BlogPart.Id == blogPostPart.BlogPart.Id && x.Month == previousMonth && x.Year == previousYear); if (previousArchiveRecord != null && previousArchiveRecord.PostCount > 0) { previousArchiveRecord.PostCount--; } // if previous count is now zero, delete the record if (previousArchiveRecord != null && previousArchiveRecord.PostCount == 0) { _blogArchiveRepository.Delete(previousArchiveRecord); } // increment new archive record var newArchiveRecord = _blogArchiveRepository .Table .FirstOrDefault(x => x.BlogPart.Id == blogPostPart.BlogPart.Id && x.Month == newMonth && x.Year == newYear); // if record can't be found create it if (newArchiveRecord == null) { newArchiveRecord = new BlogPartArchiveRecord { BlogPart = blogPostPart.BlogPart.ContentItem.Record, Year = newYear, Month = newMonth, PostCount = 0 }; _blogArchiveRepository.Create(newArchiveRecord); } newArchiveRecord.PostCount++; }
public DateTime CurrentIndianTime() { return(TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, INDIAN_ZONE)); }
public static DateTime ToTimeZone(this DateTime utcDateTime, string timeZoneId) { TimeZoneInfo userTimeZone = ToTimeZoneInfo(timeZoneId); return(TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, userTimeZone)); }
/// <summary> /// Return DateTime in the specified TimeZoneInfo. /// /// </summary> /// <param name="toTimeZone"></param> /// <returns></returns> public DateTime ConvertCurrentDateTimeToTimeZone(TimeZoneInfo toTimeZone) { return(TimeZoneInfo.ConvertTimeFromUtc(DateTime.Now.ToUniversalTime(), toTimeZone)); }
public void setDateTimeToClientTime() //call this method when you have to update record from code (not from html form). e.g. BulkUpdate { this.T_AccidentDate = TimeZoneInfo.ConvertTimeFromUtc(this.T_AccidentDate, this.m_Timezone); }
/// <summary> /// Returns TimeZone adjusted time for a given from a Utc or local time. /// Date is first converted to UTC then adjusted. /// </summary> /// <param name="time"></param> /// <param name="timeZoneId"></param> /// <returns></returns> public static DateTime ToTimeZoneTime(this DateTime time, TimeZoneInfo tzi) { return(TimeZoneInfo.ConvertTimeFromUtc(time, tzi)); }
public static DateTime WithUserOffset(this DateTime utc) { var clientTimezoneProvider = HttpContext.Current.GetService <IClientTimezoneProvider>(); return(TimeZoneInfo.ConvertTimeFromUtc(utc, clientTimezoneProvider.ClientTimezone)); }
public static DateTime NowEst() { return(TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"))); }
public static DateTime ToClientTime(this DateTime dateTime, string timeZone) { return(TimeZoneInfo.ConvertTimeFromUtc(dateTime, TimeZoneInfo.FindSystemTimeZoneById(timeZone))); }
private TemplateMapping ConvertSitecoreTemplateToModel(Item templateMapping, string projectName = null) { var fields = ConvertSitecoreFieldsToModel(templateMapping.Children); var mapping = new TemplateMapping { MappingId = templateMapping.ID.ToString(), FieldMappings = fields.ToList(), GcTemplate = new GcTemplate { GcTemplateId = templateMapping["GC Template"], GcTemplateName = templateMapping.Name, }, }; var accountSettings = _accountsRepository.GetAccountSettings(); var dateFormat = accountSettings.DateFormat; if (string.IsNullOrEmpty(dateFormat)) { dateFormat = Constants.DateFormat; } double d; var gcUpdateDate = string.Empty; if (Double.TryParse(templateMapping["Last Updated in GC"], out d)) { var posixTime = DateTime.SpecifyKind(new DateTime(1970, 1, 1), DateTimeKind.Utc); gcUpdateDate = TimeZoneInfo.ConvertTimeFromUtc(posixTime.AddMilliseconds(d * 1000), TimeZoneInfo.Local).ToString(dateFormat); } var scTemplate = GetItem(templateMapping["Sitecore Template"]); if (scTemplate != null) { mapping.CmsTemplate = new CmsTemplate { TemplateName = scTemplate.Name, TemplateId = scTemplate.ID.ToString(), TemplateFields = GetTemplateFields(scTemplate) }; mapping.LastUpdatedDate = gcUpdateDate; mapping.MappingTitle = templateMapping["Template mapping title"]; mapping.DefaultLocationId = templateMapping["Default Location"]; mapping.DefaultLocationTitle = GetItem(templateMapping["Default Location"]) != null ? GetItem(templateMapping["Default Location"]).Name : ""; mapping.LastMappedDateTime = DateUtil.IsoDateToDateTime(templateMapping["Last Mapped Date"]) .ToString(dateFormat); } else { mapping.CmsTemplate = new CmsTemplate { TemplateName = "Not mapped" }; mapping.MappingTitle = "Not mapped"; mapping.LastMappedDateTime = "never"; } if (projectName != null) { mapping.GcProjectName = projectName; } return(mapping); }
public static DateTime GetExchangeTime(string needTimeZone) { TimeZoneInfo neededTimeZone = TimeZoneInfo.FindSystemTimeZoneById(needTimeZone); return(TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, neededTimeZone)); }
public IEnumerable <ITimeZoneOffsetSegment> GetOffsetSegments(DateTime fromUtc, DateTime toUtc, string tzName) { var timeZone = this.GetTimeZone(tzName); var toLocal = TimeZoneInfo.ConvertTimeFromUtc(toUtc, timeZone); var segments = new List <TimeZoneOffsetSegment>(); var from = fromUtc; var nextCheck = from; var count = 0; while (true) { var(nextLocal, nextDelta) = this.GetNextTransition( TimeZoneInfo.ConvertTimeFromUtc(nextCheck, timeZone), timeZone); DateTime next; var isLast = nextLocal == null || nextLocal > toLocal; if (isLast) { next = toUtc; } else { next = TimeZoneInfo.ConvertTimeToUtc(nextLocal.Value + nextDelta.Value, timeZone); if (timeZone.IsInvalidTime(nextLocal.Value)) { nextCheck = next; } else { nextCheck = TimeZoneInfo.ConvertTimeToUtc(nextLocal.Value, timeZone).AddMilliseconds(1); } } segments.Add( new TimeZoneOffsetSegment { FromUtc = from, ToUtc = next, FromIncluding = true, ToIncluding = isLast, HourOffset = this.HoursOffset(from, timeZone) }); if (isLast) { break; } from = next; count++; if (count > 10000) { throw new Exception("Too many iterations"); } } return(segments); }
public DateTime ToLocal(DateTime utc) { var cstZone = TimeZoneInfo.FindSystemTimeZoneById("Romance Standard Time"); return(TimeZoneInfo.ConvertTimeFromUtc(utc, cstZone)); }
protected void btn_AddNewCapturedPaper_Click(object sender, EventArgs e) { if (ddl_PaperSet.SelectedValue == "Z") { lbl_msg.Text = "Select Paper Set first"; lbl_msg.Font.Bold = true; lbl_msg.BackColor = System.Drawing.Color.Orange; } else { if (!isPresent(tb_PaperCapturedCC.Text.Trim(), ddl_PaperSet.SelectedValue)) { using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString)) { using (SqlCommand cmd = new SqlCommand("AddPaper", con)) { SqlParameter param_courseCode = new SqlParameter("@PaperCourseCode", SqlDbType.NVarChar); SqlParameter param_DateTime = new SqlParameter("@DateTime", SqlDbType.NVarChar); SqlParameter param_Set = new SqlParameter("@Set", SqlDbType.Char); param_courseCode.Value = tb_PaperCapturedCC.Text; param_DateTime.Value = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, IST).ToShortDateString() + " " + TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, IST).ToShortTimeString(); param_Set.Value = ddl_PaperSet.SelectedValue.ToString(); cmd.Parameters.Add(param_courseCode); cmd.Parameters.Add(param_DateTime); cmd.Parameters.Add(param_Set); cmd.CommandType = CommandType.StoredProcedure; lbl_msg.ForeColor = System.Drawing.Color.White; con.Open(); if (cmd.ExecuteNonQuery() == 1) { lbl_msg.Text = "Paper added and broadcasted to all"; lbl_msg.BackColor = System.Drawing.Color.Green; } else { lbl_msg.Text = "Error occured. Call now: 9988255277"; lbl_msg.BackColor = System.Drawing.Color.Red; } } } refreshData(); } else { lbl_msg.BackColor = System.Drawing.Color.Orange; lbl_msg.Font.Bold = true; lbl_msg.Text = "Paper already captured."; } } }