public static bool CompareDate(DateTime dateToCompare, DateTime date, int minuteTolerance) { if (!dateToCompare.Equals(date)) { date = date.AddMinutes(minuteTolerance); if (!dateToCompare.Equals(date)) { date = date.AddMinutes(-2 * minuteTolerance); if (!dateToCompare.Equals(date)) { return false; } else { return true; } } else { return true; } } else { return true; } }
static int Workdays(DateTime inputDate) { DateTime today = new DateTime(); today = DateTime.Today; DateTime [] hollidays = { new DateTime(2013,5,1), new DateTime(2013,5,2), new DateTime(2013,5,3), new DateTime(2013,5,6), new DateTime(2013,5,24), new DateTime(2013,9,6), new DateTime(2013,12,24), new DateTime(2013,12,25), new DateTime(2013,12,26) }; bool isWorkday = true; int countWorkdays = 0; today = today.AddDays(1); while (today.Equals(inputDate) == false) { string day = today.DayOfWeek.ToString(); if (day.CompareTo("Sunday") == 0 || day.CompareTo("Saturday") == 0) { isWorkday = false; } if (isWorkday) { foreach (var date in hollidays) { if (today.Equals(date)) { isWorkday = false; break; } } } if (isWorkday) { countWorkdays++; } else { isWorkday = true; } today = today.AddDays(1); } return countWorkdays; }
/// <summary> /// 根据用户ID查询商品评价 /// </summary> /// <param name="userId">用户ID</param> /// <param name="appId">appId</param> /// <param name="lastReviewTime">本页最后评价时间</param> /// <returns></returns> public System.Collections.Generic.List <Jinher.AMP.BTP.Deploy.CustomDTO.ReviewSDTO> GetReviewByUserIdExt (System.Guid userId, System.Guid appId, System.DateTime lastReviewTime) { string min = "1970-01-01 08:00:00"; DateTime mintime = Convert.ToDateTime(min); if (lastReviewTime.Equals(null) || lastReviewTime.Equals(DateTime.MinValue) || lastReviewTime.Equals(mintime)) { lastReviewTime = DateTime.Now; } var query = (from r in Review.ObjectSet() where r.UserId == userId && r.AppId == appId && r.SubTime < lastReviewTime orderby r.SubTime descending select r).Take(10).ToList(); //获取所有评价id var reviewid = query.Select(n => n.Id).ToList(); var replaylist = Reply.ObjectSet().Where(n => reviewid.Contains(n.ReviewId)).ToList(); List <ReviewSDTO> reviewlist = new List <ReviewSDTO>(); foreach (var review in query) { ReviewSDTO reviewSDTO = new ReviewSDTO(); reviewSDTO.ReviewId = review.Id; reviewSDTO.UserId = review.UserId; reviewSDTO.Name = review.UserName; reviewSDTO.UserHead = review.UserHeader; reviewSDTO.Details = review.Content; reviewSDTO.SubTime = review.SubTime; reviewSDTO.ShowTime = ConvertPublishTime(review.SubTime); reviewSDTO.CommodityName = review.CommodityName; reviewSDTO.CommodityPicture = review.CommodityPicture; reviewSDTO.Size = review.CommodityAttributes; reviewSDTO.Replays = (from n in replaylist.Where(n => n.ReviewId == review.Id) select new ReplySDTO { ReplyerName = n.UserName, ReplyerHead = n.UserHeader, Details = n.ReplyDetails, ReviewId = n.Id, PreId = n.PreUserId, SubTime = n.SubTime, ShowTime = ConvertPublishTime(n.SubTime) }).OrderBy(n => n.SubTime).ToList(); reviewlist.Add(reviewSDTO); } return(reviewlist); }
public override bool Equals(object obj) { if (obj is DateValue) { return(value.Equals(((DateValue)obj).value)); } else { return(value.Equals(obj)); } }
/// <summary> /// 时间显示格式处理 /// </summary> /// <param name="d">时间值</param> /// <param name="format">格式字符串。</param> /// <returns></returns> public static string GetDateString(DateTime d, string format) { if (d == null || d.ToString() == "" || d.Equals(Utils.GetDateTime("1900-1-1 0:00:00")) || d.Equals(Utils.GetDateTime("0001-01-01 0:00:00"))) { return ""; } else { return d.ToString(format); } }
/// <summary> /// 根据商品ID查询商品评价 /// </summary> /// <param name="commodityId">商品ID</param> /// <param name="appId">appId</param> /// <param name="lastReviewTime">本页最后评价时间</param> /// <returns></returns> public System.Collections.Generic.List <Jinher.AMP.BTP.Deploy.CustomDTO.ReviewSDTO> GetReviewByCommodityIdExt (System.Guid commodityId, System.Guid appId, System.DateTime lastReviewTime) { Reply r = new Reply(); string min = "1970-01-01 08:00:00"; DateTime mintime = Convert.ToDateTime(min); if (lastReviewTime.Equals(null) || lastReviewTime.Equals(DateTime.MinValue) || lastReviewTime.Equals(mintime)) { lastReviewTime = DateTime.Now; } var query = (from data in Review.ObjectSet(). Where(n => n.CommodityId == commodityId && n.SubTime < lastReviewTime) .OrderByDescending(n => n.SubTime).Take(10) select data).ToList(); var reviewid = query.Select(n => n.Id).ToList(); var replaylist = Reply.ObjectSet().Where(n => reviewid.Contains(n.ReviewId)).ToList(); List <ReviewSDTO> reviewlist = new List <ReviewSDTO>(); foreach (var data in query) { ReviewSDTO reviewSDTO = new ReviewSDTO(); reviewSDTO.ReviewId = data.Id; reviewSDTO.UserId = data.UserId; reviewSDTO.OrderItemId = data.CommodityId; reviewSDTO.Name = ConvertAnonymous(data.UserName); reviewSDTO.UserHead = data.UserHeader; reviewSDTO.Details = data.Content; reviewSDTO.SubTime = data.SubTime; reviewSDTO.ShowTime = ConvertPublishTime(data.SubTime); reviewSDTO.Size = data.CommodityAttributes; reviewSDTO.Replays = (from n in replaylist.Where(n => n.ReviewId == data.Id) select new ReplySDTO { ReplyerName = ConvertAnonymous(n.UserName), ReplyerHead = n.UserHeader, Details = n.ReplyDetails, ReviewId = n.Id, PreId = n.PreUserId, SubTime = n.SubTime, ShowTime = ConvertPublishTime(n.SubTime) }).OrderBy(n => n.SubTime).ToList(); reviewlist.Add(reviewSDTO); } return(reviewlist); }
public void CanConvertBothDirections() { var now = DateTime.UtcNow; var nowWithoutMs = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, now.Millisecond, DateTimeKind.Utc); var rightNow = now.ToMillisecondTimestamp().ToDateTime(); Assert.IsTrue(nowWithoutMs.Equals(rightNow)); var yesterday = (nowWithoutMs.ToMillisecondTimestamp() - (long)TimeSpan.FromDays(1).TotalMilliseconds).ToDateTime(); var dayAfterTomorrow = yesterday.AddDays(1); Assert.IsTrue(nowWithoutMs.Equals(dayAfterTomorrow.ToUniversalTime())); }
public void ToDateRemovesAllTimePortion() { Date d1 = new DateTime(2001, 2, 3, 4, 5, 6, 7).AddTicks(8).ToDate(); Date d2 = new Date(2001, 2, 3); Assert.AreEqual(d1, d2); Assert.IsTrue(d1.Equals(d2)); }
/// <summary> /// Method to take screenshot from primary screen, change it's creation time and save it into the folder /// </summary> /// <param name="creationTime"></param> /// <param name="screenPath"></param> /// <returns></returns> public static string TakeScreenshot(DateTime creationTime = default(DateTime), string screenPath = "") { var format = ImageFormat.Png; var now = DateTime.Now; creationTime = creationTime.Equals(default(DateTime)) ? now : creationTime; var screenName = GetScreenName(creationTime, format); using (var bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height)) { using (var g = Graphics.FromImage(bmpScreenCapture)) { g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, bmpScreenCapture.Size, CopyPixelOperation.SourceCopy); var file = (screenPath.Equals("") ? GetPath() : screenPath) + screenName; bmpScreenCapture.Save(file, format); var fileInfo = new FileInfo(file); fileInfo.Refresh(); fileInfo.CreationTime = creationTime; } } return screenName; }
public static System.Data.DataSet GetMovimientosDeCajaPosterioresA(System.DateTime fechaUltimoControlDeCaja, string IdInstanciaCaja) { System.Data.DataSet data = new DataSet(); try { SqlDataAdapter adapter = new SqlDataAdapter(); SqlCommand cmd = new SqlCommand("Pr_tfi_Cajas_MovimientosDeCajaPosterioresA", dbhelper.Connection.GetConnection()); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@Fecha", SqlDbType.DateTime)); if (fechaUltimoControlDeCaja.Equals(DateTime.MinValue)) { cmd.Parameters["@Fecha"].Value = System.DBNull.Value; } else { cmd.Parameters["@Fecha"].Value = fechaUltimoControlDeCaja; } cmd.Parameters.Add(new SqlParameter("@IdInstanciaCaja", SqlDbType.VarChar)); cmd.Parameters["@IdInstanciaCaja"].Value = IdInstanciaCaja; adapter.SelectCommand = cmd; adapter.Fill(data, "Result"); } catch (Exception e) { System.Console.WriteLine(e.ToString()); } return(data); }
private string SerieData() { string data = ""; var transactions = (from trs in db.Transactions group trs by new { Year = trs.Date.Year, Month = trs.Date.Month, Day = trs.Date.Day } into g orderby g.Key.Year, g.Key.Month, g.Key.Day select new { Year = g.Key.Year, Month = g.Key.Month, Day = g.Key.Day, Value = g.Max(i=>i.Rest) }) .ToList(); var value = transactions.First().Value; DateTime date = new DateTime(transactions.First().Year, transactions.First().Month, transactions.First().Day).Date; foreach (var transaction in transactions) { DateTime transactionDate = new DateTime(transaction.Year, transaction.Month, transaction.Day).Date; while (!transactionDate.Equals(date)) { data += "[Date.UTC(" + date.Year.ToString() + "," + (date.Month - 1).ToString() + "," + date.Day.ToString() + ")," + value.ToString().Replace(',', '.') + "]," ; date = date.AddDays(1); } value = transaction.Value; date = transactionDate; data += "[Date.UTC(" + transaction.Year.ToString() + "," + (transaction.Month - 1).ToString() + "," + transaction.Day.ToString() + ")," + transaction.Value.ToString().Replace(',', '.') + "]," ; } return "[" + data.Remove(data.Length - 1) + "]"; }
protected ElectionEvent(DateTime date, string name) { Contract.Requires(!date.Equals(null)); Contract.Requires(!string.IsNullOrEmpty(name)); _date = date; _name = name; }
static bool IsPublicHoliday(DateTime date) { bool isHoliday = false; List<DateTime> publicHolidaysList = new List<DateTime>(); publicHolidaysList.Add(Convert.ToDateTime("1.1.2015")); publicHolidaysList.Add(Convert.ToDateTime("2.1.2015")); publicHolidaysList.Add(Convert.ToDateTime("3.3.2015")); publicHolidaysList.Add(Convert.ToDateTime("10.4.2015")); publicHolidaysList.Add(Convert.ToDateTime("13.4.2015")); publicHolidaysList.Add(Convert.ToDateTime("1.5.2015")); publicHolidaysList.Add(Convert.ToDateTime("6.5.2015")); publicHolidaysList.Add(Convert.ToDateTime("24.5.2015")); publicHolidaysList.Add(Convert.ToDateTime("6.9.2015")); publicHolidaysList.Add(Convert.ToDateTime("22.9.2015")); publicHolidaysList.Add(Convert.ToDateTime("24.12.2015")); publicHolidaysList.Add(Convert.ToDateTime("25.12.2015")); foreach (var holiday in publicHolidaysList) { if (date.Equals(holiday)) { isHoliday = true; break; } } return isHoliday; }
DateTime? RepairDate(DateTime? datetime) { if (datetime.HasValue && datetime.Equals(DateTime.MinValue)) return null; return datetime; }
public static bool DateInBetween(DateTime targetDate, DateTime start, DateTime end) { try { if (targetDate != null && targetDate != default(DateTime)) { if (start.Equals(default(DateTime))) { return true; } if (start.CompareTo(targetDate) < 0) { if (end.Equals(default(DateTime))) return true; else if (end != default(DateTime) && end.CompareTo(targetDate) > 0) return true; else return false; } } } catch (Exception ex) { Utility.WriteLogError("Exception Occurred in verification of Dates" + ex.ToString()); } return false; }
static int CalculateWorkDays(DateTime today, DateTime date) { bool isHoliday = false; int numberOfWorkDays = 0; while (today.CompareTo(date) != 1) { isHoliday = false; foreach (DateTime holiday in holidays) { if (today.Equals(holiday)) { isHoliday = true; break; } } if (!isHoliday && today.DayOfWeek != DayOfWeek.Saturday && today.DayOfWeek != DayOfWeek.Sunday) { numberOfWorkDays++; } today = today.AddDays(1); } return numberOfWorkDays; }
public static object ReturnNullIfEmpty(DateTime value) { if (value.Equals(DateTime.MinValue)) return null; return value; }
public static System.Data.DataSet GetConsultaDeCajaDetallado(string IdMonedaReferencia, string IdEntidades, string IdTDCompTesoreria, System.DateTime FechaDesde, System.DateTime FechaHasta, string IdPersona, string Estado, string IdCajas, string Moneda, string EstadoCajas) { System.Data.DataSet data = new DataSet(); SqlDataAdapter adapter = new SqlDataAdapter(); SqlCommand cmd = new SqlCommand("Pr_tfi_Cajas_ConsultaTDCompTesoreria", dbhelper.Connection.GetConnection()); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandTimeout = Sistema.GetTimeout(cmd.CommandText); cmd.Parameters.Add(new SqlParameter("@IdMonedaReferencia", SqlDbType.VarChar)); cmd.Parameters["@IdMonedaReferencia"].Value = IdMonedaReferencia; cmd.Parameters.Add(new SqlParameter("@IdEntidades", SqlDbType.VarChar)); cmd.Parameters["@IdEntidades"].Value = IdEntidades; cmd.Parameters.Add(new SqlParameter("@IdTDCompTesoreria", SqlDbType.VarChar)); cmd.Parameters["@IdTDCompTesoreria"].Value = IdTDCompTesoreria; cmd.Parameters.Add(new SqlParameter("@FechaDesde", SqlDbType.DateTime)); if (FechaDesde.Equals(DateTime.MinValue)) { cmd.Parameters["@FechaDesde"].Value = System.DBNull.Value; } else { cmd.Parameters["@FechaDesde"].Value = FechaDesde; } cmd.Parameters.Add(new SqlParameter("@FechaHasta", SqlDbType.DateTime)); if (FechaHasta.Equals(DateTime.MinValue)) { cmd.Parameters["@FechaHasta"].Value = System.DBNull.Value; } else { cmd.Parameters["@FechaHasta"].Value = FechaHasta; } cmd.Parameters.Add(new SqlParameter("@IdPersona", SqlDbType.VarChar)); cmd.Parameters["@IdPersona"].Value = IdPersona; cmd.Parameters.Add(new SqlParameter("@Estado", SqlDbType.VarChar)); cmd.Parameters["@Estado"].Value = Estado; cmd.Parameters.Add(new SqlParameter("@IdCajas", SqlDbType.VarChar)); cmd.Parameters["@IdCajas"].Value = IdCajas; cmd.Parameters.Add(new SqlParameter("@Moneda", SqlDbType.VarChar)); cmd.Parameters["@Moneda"].Value = Moneda; cmd.Parameters.Add(new SqlParameter("@EstadoCajas", SqlDbType.VarChar)); cmd.Parameters["@EstadoCajas"].Value = EstadoCajas; adapter.SelectCommand = cmd; adapter.Fill(data, "Result"); return(data); }
public static string FormatDate(DateTime dateTime) { if (dateTime.Equals(DateTime.MinValue)) return string.Empty; if (DateTime.Now.Subtract(dateTime).TotalDays > 365) return dateTime.ToString("yyyy"); return DateTime.Now.Year == dateTime.Year ? dateTime.ToString("MM-dd") : dateTime.ToString("yyyy-MM-dd"); }
/// <summary> /// Compares this DateTimeCompare to another DateTimeCompare. /// </summary> /// <param name="other">The other DateTimeCompare.</param> /// <returns>True if the two DateTimeCompare values are equal.</returns> public bool Equals(DateTimeCompare other) { if (object.ReferenceEquals(other, null) || GetType() != other.GetType()) { return(false); } return(_dateTime.Equals(other.Value)); }
public bool Equals(Date other) { if (ReferenceEquals(null, other)) { return(false); } return(ReferenceEquals(this, other) || _internal.Equals(other._internal)); }
protected bool DateValidation(DateTime date) { DateTime fakeDate = new DateTime(0001, 01, 01); if (date.Equals(fakeDate) || date.CompareTo(DateTime.Today) < 0) return false; else return true; }
protected object CheckParamValue(DateTime paramValue) { if (paramValue.Equals(DefaultConstants.NullDateTime)) { return DBNull.Value; } return paramValue; }
public static bool IsEmptyDate(DateTime date) { if (date.Equals(DateTime.MinValue)) { return true; } return false; }
/// <summary> /// Create and return a <DATE> element for the given XML document /// </summary> /// <param name="doc">Document with which to create the element</param> /// <param name="dateTime">Value to represent in XML</param> /// <returns>XmlElement representing the date</returns> /// <remarks>This method always includes the Relative attribute. See overloaded methods for other options.</remarks> public static XmlElement GetDateTimeAsElement(XmlDocument doc, DateTime dateTime) { if (dateTime.Equals(DateTime.MinValue)) { return GetDefaultDateTimeAsElement(doc); } return GetDateTimeAsElement(doc, dateTime, true); }
public List<Order> GetManagementOrders(int orderID, DateTime? fromdate,DateTime? todate, int orderStatus, int customerID) { return db.Orders.Where(u => (orderID.Equals(0) || orderID.Equals(null) || u.ID.Equals(orderID)) && (fromdate.Equals(null) || u.DateCreated >= fromdate) && (todate.Equals(null) || u.DateCreated <= todate) && (orderStatus.Equals(0) || orderStatus.Equals(null) || u.OrderStatus_ID.Equals(orderStatus)) && (customerID.Equals(0) || customerID.Equals(null) || u.Customer_ID.Value.Equals(customerID)) ).OrderByDescending(u => u.ID).ToList(); }
private void AssertAreEqual(DateTime expected, DateTime actual) { if (expected.Equals(new DateTime(DatePlatform.MaxDate)) && Db4oHandlerVersion() == 0) { // Bug in the oldest format: It treats a Long.MAX_VALUE date as null. expected = MarshallingConstants0.NullDate; } Assert.AreEqual(expected, actual); }
public Date(DateTime dateTime) { if (dateTime.Equals(DateTime.MinValue)) isUnknown = true; else { this.dateTime = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day); isUnknown = false; } }
/// <summary> /// Convert 1 chuổi ngày kiểu Date thành kiểu String /// </summary> public static string DateToString(string format, System.DateTime date) { if (date.Equals(null)) { return(""); } else { return(date.ToString(format, System.Globalization.DateTimeFormatInfo.CurrentInfo)); } }
/// <summary> /// 将时间格式化成 时分秒 的形式,如果时间为null,返回当前系统时间 /// </summary> /// <param name="dt"></param> /// <param name="Separator"></param> /// <returns></returns> public string GetFormatTime(DateTime dt, char Separator) { if (dt != null && !dt.Equals(DBNull.Value)) { string tem = string.Format("hh{0}mm{1}ss", Separator, Separator); return dt.ToString(tem); } else { return GetFormatDate(DateTime.Now, Separator); } }
public System.DateTime txtFieldDate(string dateValue, string format) { System.DateTime myDate = System.DateTime.MinValue; if (dateValue.Trim() != "") { try { if (format == "") { myDate = System.DateTime.Parse(dateValue); } else { myDate = DateTime.ParseExact(dateValue, format, new System.Globalization.CultureInfo("en-US")); } } catch { } if (myDate.Equals(System.DateTime.MinValue)) { int Year = 0; int Month = 0; int Day = 0; int Hour = 0; int Min = 0; int Sec = 0; try { int Ypos = format.IndexOf("yyyy"); int Mpos = format.IndexOf("MM"); int Dpos = format.IndexOf("dd"); Year = int.Parse(dateValue.Substring(Ypos, 4)); Month = int.Parse(dateValue.Substring(Mpos, 2)); Day = int.Parse(dateValue.Substring(Dpos, 2)); myDate = new System.DateTime(Year, Month, Day); } catch {} try { int Hpos = format.IndexOf("HH"); int Npos = format.IndexOf("mm"); int Spos = format.IndexOf("ss"); Hour = int.Parse(dateValue.Substring(Hpos, 2)); Min = int.Parse(dateValue.Substring(Npos, 2)); Sec = int.Parse(dateValue.Substring(Spos, 2)); myDate = new System.DateTime(Year, Month, Day, Hour, Min, Sec); } catch {} } } return(myDate); }
/// <summary> /// Leiab kuupäeva järgi DcfData objekti /// </summary> /// <param name="kp">Kuupäev</param> /// <returns>Leitud DcfData objekt</returns> public DcfData GetDcfData(DateTime kp) { foreach (var dcfData in _dcfDatas) { if (kp.Equals(dcfData.Kuupaev)) { return dcfData; } } return null; }
public string GetDataValue(DateTime value) { if (value.Equals(null) ) { return string.Empty; } else { return value.ToString(); } }
/// <summary> /// Kuupäeva järgi FinData objekti leidmine /// </summary> /// <param name="kp">Kuupäev</param> /// <returns>FinData objekt</returns> public FinData GetFinData(DateTime kp) { foreach (FinData finData in _finDatas) { if (kp.Equals(finData.Kuupaev)) { return finData; } } return null; }
public string GetFormatDate(DateTime dt, char Separator) { if (!dt.Equals(DBNull.Value)) { string tem = $"yyyy{Separator}MM{Separator}dd"; return dt.ToString(tem); } else { return GetFormatDate(DateTime.Now, Separator); } }
public List<ContaPagar> ObterLista(int codigoCompra, int codigoFornecedor, DateTime dataEmissao, DateTime dataVencimento, int statusContaPagar, string nomeFornecedor, string documento, int codigoUsuario) { var query = from contaPagar in _context.ContasPagar .Include("Compra") .Include("Compra.Usuario") .Include("Compra.Fornecedor.PessoaFisica") .Include("Compra.Fornecedor.PessoaJuridica") select contaPagar; if (!codigoCompra.Equals(0)) { query = query.Where(x => x.Compra.CompraCodigo == codigoCompra); } if (!codigoFornecedor.Equals(0)) { query = query.Where(x => x.Compra.Fornecedor.PessoaCodigo == codigoFornecedor); } if (!dataEmissao.Equals(new DateTime())) { query = query.Where(x => EntityFunctions.TruncateTime(x.Compra.DataCadastro) == dataEmissao.Date); } if (!dataVencimento.Equals(new DateTime())) { query = query.Where(x => EntityFunctions.TruncateTime(x.DataVencimento) == dataVencimento.Date); } if (!statusContaPagar.Equals(0)) { query = query.Where(x => (int)x.StatusContaPagar == statusContaPagar); } if (!string.IsNullOrEmpty(nomeFornecedor)) { query = query.Where(x => x.Compra.Fornecedor.Nome == nomeFornecedor); } if (!string.IsNullOrEmpty(documento)) { query = query.Where(x => x.Compra.Fornecedor.PessoaFisica.CPF == documento || x.Compra.Fornecedor.PessoaJuridica.CNPJ == documento); } if (!codigoUsuario.Equals(0)) { query = query.Where(x => x.Compra.Usuario.UsuarioCodigo == codigoUsuario); } return query.ToList(); }
public List<ContaReceber> ObterLista(int codigoVenda, int codigoCliente, DateTime dataEmissao, DateTime dataVencimento, int statusContaReceber, string nomeCliente, string documento, int codigoUsuario) { var query = from contaReceber in _context.ContasReceber .Include("Venda") .Include("Venda.Usuario") .Include("Venda.Cliente.PessoaFisica") .Include("Venda.Cliente.PessoaJuridica") select contaReceber; if (!codigoVenda.Equals(0)) { query = query.Where(x => x.Venda.VendaCodigo == codigoVenda); } if (!codigoCliente.Equals(0)) { query = query.Where(x => x.Venda.Cliente.PessoaCodigo == codigoCliente); } if (!dataEmissao.Equals(new DateTime())) { query = query.Where(x => EntityFunctions.TruncateTime(x.Venda.DataCadastro) == dataEmissao.Date); } if (!dataVencimento.Equals(new DateTime())) { query = query.Where(x => EntityFunctions.TruncateTime(x.DataVencimento) == dataVencimento.Date); } if (!statusContaReceber.Equals(0)) { query = query.Where(x => (int)x.StatusContaReceber == statusContaReceber); } if (!string.IsNullOrEmpty(nomeCliente)) { query = query.Where(x => x.Venda.Cliente.Nome == nomeCliente); } if (!string.IsNullOrEmpty(documento)) { query = query.Where(x => x.Venda.Cliente.PessoaFisica.CPF == documento || x.Venda.Cliente.PessoaJuridica.CNPJ == documento); } if (!codigoUsuario.Equals(0)) { query = query.Where(x => x.Venda.Usuario.UsuarioCodigo == codigoUsuario); } return query.ToList(); }
public ILPFlow(Int64 testNumber,string loanNumber, string email,DateTime start,DateTime finish, int applicationForm,int privacyPolicy,int upSell,int eSign,int thankYou) { this.TestNumber = testNumber; this.LoanNumber = loanNumber; this.Email = email; this.Start = (start.Equals(DateTime.MinValue))?String.Empty: start.ToString("MM/dd/yyyy hh:mm:ss"); this.Finish = (finish.Equals(DateTime.MinValue))?String.Empty:finish.ToString("MM/dd/yyyy hh:mm:ss"); this.ApplicationForm = applicationForm; this.PrivacyPolicy = privacyPolicy; this.UpSell = upSell; this.ESign = eSign; this.ThankYou = thankYou; }
/// <summary> /// Utility method for sampling the sensor readings according to a specified time samples. /// </summary> /// <param name="sensorReadings">Sensor readings to be sampled</param> /// <param name="startTime">The initial/start time which serves as base for calculating sample periods.</param> /// <param name="samplingHours">The hours component of the sample period duration.</param> /// <param name="samplingMinutes">The minutes component of the sample period duration.</param> /// <param name="samplingSeconds">The seconds component of the sample period duration.</param> /// <returns></returns> public static List <BaseSensorReading>[] SampleSensorReadings(List <BaseSensorReading> sensorReadings, System.DateTime startTime, int samplingHours, int samplingMinutes, int samplingSeconds) { List <List <BaseSensorReading> > sensorReadingsSamples = new List <List <BaseSensorReading> >(); // Calculate next end of sampling period System.DateTime nextSamplePeriod = startTime; nextSamplePeriod = nextSamplePeriod.Date + new System.TimeSpan(samplingHours + nextSamplePeriod.Hour, samplingMinutes + nextSamplePeriod.Minute, samplingSeconds + nextSamplePeriod.Second); // Do nothing if quantised period was not set if (!nextSamplePeriod.Equals(startTime)) { List <BaseSensorReading> sensorReadingSample = new List <BaseSensorReading>(); foreach (BaseSensorReading aSensorReading in sensorReadings) { // If within sampling period, add it if (aSensorReading.dateTime <= nextSamplePeriod) { sensorReadingSample.Add(aSensorReading); } else { // Add current sample if there are sensor readings in it if (sensorReadingSample.Count != 0) { sensorReadingsSamples.Add(sensorReadingSample); } // Clear sample to represent next sample period + add current sensor reading sensorReadingSample.Clear(); sensorReadingSample.Add(aSensorReading); // Calculate next end of sampling period nextSamplePeriod = nextSamplePeriod.Date + new System.TimeSpan(samplingHours + nextSamplePeriod.Hour, samplingMinutes + nextSamplePeriod.Minute, samplingSeconds + nextSamplePeriod.Second); } } // If current sample not empty + reached end of sensor readings -> add as last sample if (sensorReadingSample.Count != 0) { sensorReadingsSamples.Add(sensorReadingSample); } } return(sensorReadingsSamples.ToArray()); }
public static System.Data.DataSet GetConsultasCobranzasYPagosAbiertas(string IdCaja, System.DateTime fechaApertura, System.DateTime fechaCierre, string IdResponsable, string IdTipo, string EstadoCajas) { System.Data.DataSet data = new DataSet(); try { SqlDataAdapter adapter = new SqlDataAdapter(); SqlCommand cmd = new SqlCommand("Pr_tfi_Cajas_CobranzasYPagosAbierta", dbhelper.Connection.GetConnection()); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandTimeout = Sistema.GetTimeout(cmd.CommandText); cmd.Parameters.Add(new SqlParameter("@IdCaja", SqlDbType.VarChar)); cmd.Parameters["@IdCaja"].Value = IdCaja; cmd.Parameters.Add(new SqlParameter("@fechaApertura", SqlDbType.DateTime)); if (fechaApertura.Equals(DateTime.MinValue)) { cmd.Parameters["@FechaApertura"].Value = System.DBNull.Value; } else { cmd.Parameters["@FechaApertura"].Value = fechaApertura; } cmd.Parameters.Add(new SqlParameter("@FechaCierre", SqlDbType.DateTime)); if (fechaCierre.Equals(DateTime.MinValue)) { cmd.Parameters["@FechaCierre"].Value = System.DBNull.Value; } else { cmd.Parameters["@FechaCierre"].Value = fechaCierre; } cmd.Parameters.Add(new SqlParameter("@IdResponsable", SqlDbType.VarChar)); cmd.Parameters["@IdResponsable"].Value = IdResponsable; cmd.Parameters.Add(new SqlParameter("@IdTipoDeMovimiento", SqlDbType.VarChar)); cmd.Parameters["@IdTipoDeMovimiento"].Value = IdTipo; cmd.Parameters.Add(new SqlParameter("@EstadoCajas", SqlDbType.VarChar)); cmd.Parameters["@EstadoCajas"].Value = EstadoCajas; adapter.SelectCommand = cmd; adapter.Fill(data, "Result"); } catch (Exception e) { System.Console.WriteLine(e.ToString()); } return(data); }
//però se ho tutto uguale e solo la lastModified diversa dovrei considerarla la stessa???? //forse non dovrei avere la lastModified in memoria? public override bool Equals(object obj) { RecordFile r = obj as RecordFile; if (r == null) { return(false); } if (nameAndPath.Equals(r.nameAndPath) && hash.Equals(r.hash) && //size.Equals(r.size) && il size può essere a -1 lastModified.Equals(r.lastModified)) { return(true); } return(false); }
public static System.Data.DataSet GetConsultaDeGastos(string IdCaja, System.DateTime fechaApertura, System.DateTime fechaCierre, string IdTipo) { System.Data.DataSet data = new DataSet(); try { SqlDataAdapter adapter = new SqlDataAdapter(); SqlCommand cmd = new SqlCommand("Pr_tfi_MovimientosDeCaja_ListadoDeMovimientos", dbhelper.Connection.GetConnection()); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandTimeout = Sistema.GetTimeout(cmd.CommandText); cmd.Parameters.Add(new SqlParameter("@IdCaja", SqlDbType.VarChar)); cmd.Parameters["@IdCaja"].Value = IdCaja; cmd.Parameters.Add(new SqlParameter("@fechaDesde", SqlDbType.DateTime)); if (fechaApertura.Equals(DateTime.MinValue)) { cmd.Parameters["@FechaDesde"].Value = System.DBNull.Value; } else { cmd.Parameters["@FechaDesde"].Value = mz.erp.systemframework.Util.GetStartDay(fechaApertura); } cmd.Parameters.Add(new SqlParameter("@FechaHasta", SqlDbType.DateTime)); if (fechaCierre.Equals(DateTime.MinValue)) { cmd.Parameters["@FechaHasta"].Value = System.DBNull.Value; } else { cmd.Parameters["@FechaHasta"].Value = mz.erp.systemframework.Util.GetEndDay(fechaCierre); } cmd.Parameters.Add(new SqlParameter("@IdTipoDeMovimiento", SqlDbType.VarChar)); cmd.Parameters["@IdTipoDeMovimiento"].Value = IdTipo; adapter.SelectCommand = cmd; adapter.Fill(data, "Result"); } catch (Exception e) { System.Console.WriteLine(e.ToString()); } return(data); }
public static System.Data.DataSet GetAuditoriaCajasCerradas(string IdCajas, System.DateTime fechaApertura, System.DateTime fechaCierre) { System.Data.DataSet data = new DataSet(); try { SqlDataAdapter adapter = new SqlDataAdapter(); SqlCommand cmd = new SqlCommand("Pr_tfi_AuditoriaControlCajas_GetAuditoriaCajasCerradas", dbhelper.Connection.GetConnection()); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandTimeout = Sistema.GetTimeout(cmd.CommandText); cmd.Parameters.Add(new SqlParameter("@IdCajas", SqlDbType.VarChar)); cmd.Parameters["@IdCajas"].Value = IdCajas; cmd.Parameters.Add(new SqlParameter("@fechaApertura", SqlDbType.DateTime)); if (fechaApertura.Equals(DateTime.MinValue)) { cmd.Parameters["@FechaApertura"].Value = System.DBNull.Value; } else { cmd.Parameters["@FechaApertura"].Value = fechaApertura; } cmd.Parameters.Add(new SqlParameter("@FechaCierre", SqlDbType.DateTime)); if (fechaCierre.Equals(DateTime.MinValue)) { cmd.Parameters["@FechaCierre"].Value = System.DBNull.Value; } else { cmd.Parameters["@FechaCierre"].Value = fechaCierre; } adapter.SelectCommand = cmd; adapter.Fill(data, "Result"); } catch (Exception e) { System.Console.WriteLine(e.ToString()); } return(data); }
protected DateTimeResolutionResult MatchWeekdayAndDay(string text, DateObject reference) { var ret = new DateTimeResolutionResult(); // Handling cases like 'Monday 21', which both 'Monday' and '21' refer to the same date. // The year of expected date can be different to the year of referenceDate. var match = this.config.WeekDayAndDayRegex.Match(text); if (match.Success) { int month = reference.Month, year = reference.Year; // Create a extract result which content ordinal string of text ExtractResult ertmp = new ExtractResult { Text = match.Groups["day"].Value, Start = match.Groups["day"].Index, Length = match.Groups["day"].Length, }; // Parse the day in text into number var day = ConvertCJKToNum(match.Groups["day"].Value); // Firstly, find a latest date with the "day" as pivotDate. // Secondly, if the pivotDate equals the referenced date, in other word, the day of the referenced date is exactly the "day". // In this way, check if the pivotDate is the weekday. If so, then the futureDate and the previousDate are the same date (referenced date). // Otherwise, increase the pivotDate month by month to find the latest futureDate and decrease the pivotDate month // by month to the latest previousDate. // Notice: if the "day" is larger than 28, some months should be ignored in the increase or decrease procedure. var pivotDate = new DateObject(year, month, 1); var daysInMonth = DateObject.DaysInMonth(year, month); if (daysInMonth >= day) { pivotDate = DateObject.MinValue.SafeCreateFromValue(year, month, day); } else { // Add 1 month is enough, since 1, 3, 5, 7, 8, 10, 12 months has 31 days pivotDate = pivotDate.AddMonths(1); pivotDate = DateObject.MinValue.SafeCreateFromValue(pivotDate.Year, pivotDate.Month, day); } var numWeekDayInt = (int)pivotDate.DayOfWeek; var extractedWeekDayStr = match.Groups["weekday"].Value; var weekDay = this.config.DayOfWeek[extractedWeekDayStr]; if (!pivotDate.Equals(DateObject.MinValue)) { if (numWeekDayInt == weekDay) { // The referenceDate is the weekday and with the "day". ret.FutureValue = new DateObject(year, month, day); ret.PastValue = new DateObject(year, month, day); ret.Timex = DateTimeFormatUtil.LuisDate(year, month, day); } else { var futureDate = pivotDate; var pastDate = pivotDate; while ((int)futureDate.DayOfWeek != weekDay || futureDate.Day != day || futureDate < reference) { // Increase the futureDate month by month to find the expected date (the "day" is the weekday) and // make sure the futureDate not less than the referenceDate. futureDate = futureDate.AddMonths(1); var tmp = DateObject.DaysInMonth(futureDate.Year, futureDate.Month); if (tmp >= day) { // For months like January 31, after add 1 month, February 31 won't be returned, so the day should be revised ASAP. futureDate = futureDate.SafeCreateFromValue(futureDate.Year, futureDate.Month, day); } } ret.FutureValue = futureDate; while ((int)pastDate.DayOfWeek != weekDay || pastDate.Day != day || pastDate > reference) { // Decrease the pastDate month by month to find the expected date (the "day" is the weekday) and // make sure the pastDate not larger than the referenceDate. pastDate = pastDate.AddMonths(-1); var tmp = DateObject.DaysInMonth(pastDate.Year, pastDate.Month); if (tmp >= day) { // For months like March 31, after minus 1 month, February 31 won't be returned, so the day should be revised ASAP. pastDate = pastDate.SafeCreateFromValue(pastDate.Year, pastDate.Month, day); } } ret.PastValue = pastDate; if (weekDay == 0) { weekDay = 7; } ret.Timex = DateTimeFormatUtil.LuisDate(pastDate); } } ret.Success = true; return(ret); } return(ret); }
private DateTimeResolutionResult ParseDuration(string text, DateObject referenceDate) { var ret = new DateTimeResolutionResult(); var ers = config.DurationExtractor.Extract(text); if (ers.Count == 1) { var pr = config.DurationParser.Parse(ers[0]); var beforeStr = text.Substring(0, pr.Start ?? 0).Trim().ToLowerInvariant(); if (pr.Value != null) { var durationResult = (DateTimeResolutionResult)pr.Value; if (string.IsNullOrEmpty(durationResult.Timex)) { return(ret); } DateObject beginDate; var endDate = beginDate = referenceDate; var prefixMatch = config.PastRegex.Match(beforeStr); if (prefixMatch.Success) { beginDate = GetSwiftDate(endDate, durationResult.Timex, false); } prefixMatch = config.FutureRegex.Match(beforeStr); if (prefixMatch.Success && prefixMatch.Length == beforeStr.Length) { //for future the beginDate should add 1 first beginDate = referenceDate.AddDays(1); endDate = GetSwiftDate(beginDate, durationResult.Timex, true); } //handle the "in two weeks" case which means the second week prefixMatch = config.InConnectorRegex.Match(beforeStr); if (prefixMatch.Success && prefixMatch.Length == beforeStr.Length) { beginDate = referenceDate.AddDays(1); endDate = GetSwiftDate(beginDate, durationResult.Timex, true); //change the duration value and the beginDate var unit = durationResult.Timex.Substring(durationResult.Timex.Length - 1); durationResult.Timex = "P1" + unit; beginDate = GetSwiftDate(endDate, durationResult.Timex, false); } if (beginDate.Equals(endDate)) { return(ret); } endDate = InclusiveEndPeriod ? endDate.AddDays(-1) : endDate; ret.Timex = $"({FormatUtil.LuisDate(beginDate)},{FormatUtil.LuisDate(endDate)},{durationResult.Timex})"; ret.FutureValue = ret.PastValue = new Tuple <DateObject, DateObject>(beginDate, endDate); ret.Success = true; return(ret); } } return(ret); }
// MARK - Lab 2 public override bool Equals(object obj) { Person other = obj as Person; if (other != null) { return(_firstName.Equals(other._firstName) && _lastName.Equals(other._lastName) && _birthDate.Equals(other._birthDate)); } return(false); }
/// <summary /> public bool Equals(DateTime other) { return(_dateTime.Equals(other._dateTime)); }
// Compares two DateTimeOffset values for equality. Returns true if // the two DateTimeOffset values are equal, or false if they are // not equal. // public static bool Equals(DateTimeOffset first, DateTimeOffset second) { return(DateTime.Equals(first.UtcDateTime, second.UtcDateTime)); }
public override void OnInspectorGUI() { serializedObject.Update(); GUI.changed = false; SolarSystem solar = (SolarSystem)target; if (!sunMassOk) { CheckSunMass(solar); } float planetScale = 0; float epochTime = solar.epochTime; bool epochFoldout; GameObject planetPrefab = null; GameObject asteroidPrefab = null; GameObject cometPrefab = null; EditorGUIUtility.labelWidth = 200f; planetScale = EditorGUILayout.FloatField(new GUIContent("Planet size per 10000km"), solar.planetScale); EditorGUIUtility.labelWidth = 0f; // reset System.DateTime datetime = SolarUtils.DateForEpoch(solar.epochTime); epochFoldout = EditorGUILayout.Foldout(solar.epochFoldout, "Start date: " + datetime.ToString("yyyy-MM-dd")); if (epochFoldout) { EditorGUILayout.LabelField("Press ENTER to update changes in start date."); int year = EditorGUILayout.DelayedIntField("YYYY", datetime.Year); int month = EditorGUILayout.DelayedIntField("MM", datetime.Month); int day = EditorGUILayout.DelayedIntField("DD", datetime.Day); System.DateTime newTime = new System.DateTime(year, month, day); Debug.LogFormat("newTime={0}", newTime.Ticks); if (!newTime.Equals(datetime)) { epochTime = SolarUtils.DateTimeToEpoch(newTime); } } EditorGUILayout.LabelField("Prefabs", EditorStyles.boldLabel); planetPrefab = (GameObject)EditorGUILayout.ObjectField( new GUIContent("Planet Prefab", "Game object with NBody"), solar.planetPrefab, typeof(GameObject), true); asteroidPrefab = (GameObject)EditorGUILayout.ObjectField( new GUIContent("Asteroid Prefab", "Game object with NBody"), solar.asteroidPrefab, typeof(GameObject), true); cometPrefab = (GameObject)EditorGUILayout.ObjectField( new GUIContent("Comet Prefab", "Game object with NBody"), solar.cometPrefab, typeof(GameObject), true); if (GUILayout.Button("Add Body")) { SolarBodyCreatorWindow.Init(); } // Apply changes to the serializedProperty // - always do this in the end of OnInspectorGUI. // Checking the Event type lets us update after Undo and Redo commands. if (Event.current.type == EventType.ExecuteCommand && Event.current.commandName == "UndoRedoPerformed") { // explicitly re-set so setter code will run solar.planetScale = planetScale; solar.epochTime = epochTime; } if (GUI.changed) { Undo.RecordObject(solar, "Solar System Change"); solar.planetScale = planetScale; solar.epochFoldout = epochFoldout; // epochTime runs a setter that updates the objects in the scene solar.epochTime = epochTime; solar.planetPrefab = planetPrefab; solar.asteroidPrefab = asteroidPrefab; solar.cometPrefab = cometPrefab; EditorUtility.SetDirty(solar); } }
// Match several other cases // Including 'today', 'the day after tomorrow', 'on 13' private DateTimeResolutionResult ParseImplicitDate(string text, DateObject referenceDate) { var trimmedText = text.Trim(); var ret = new DateTimeResolutionResult(); // Handle "on 12" var match = this.config.OnRegex.Match(this.config.DateTokenPrefix + trimmedText); if (match.Success && match.Index == 3 && match.Length == trimmedText.Length) { int month = referenceDate.Month, year = referenceDate.Year; var dayStr = match.Groups["day"].Value; var day = this.config.DayOfMonth[dayStr]; ret.Timex = DateTimeFormatUtil.LuisDate(-1, -1, day); DateObject futureDate, pastDate; var tryStr = DateTimeFormatUtil.LuisDate(year, month, day); if (DateObject.TryParse(tryStr, out DateObject _)) { futureDate = DateObject.MinValue.SafeCreateFromValue(year, month, day); pastDate = DateObject.MinValue.SafeCreateFromValue(year, month, day); if (futureDate < referenceDate) { futureDate = futureDate.AddMonths(+1); } if (pastDate >= referenceDate) { pastDate = pastDate.AddMonths(-1); } } else { futureDate = DateObject.MinValue.SafeCreateFromValue(year, month + 1, day); pastDate = DateObject.MinValue.SafeCreateFromValue(year, month - 1, day); } ret.FutureValue = futureDate; ret.PastValue = pastDate; ret.Success = true; return(ret); } // Handle "today", "the day before yesterday" var exactMatch = this.config.SpecialDayRegex.MatchExact(trimmedText, trim: true); if (exactMatch.Success) { var swift = GetSwiftDay(exactMatch.Value); var value = referenceDate.Date.AddDays(swift); ret.Timex = DateTimeFormatUtil.LuisDate(value); ret.FutureValue = ret.PastValue = value; ret.Success = true; return(ret); } // Handle "two days from tomorrow" exactMatch = this.config.SpecialDayWithNumRegex.MatchExact(trimmedText, trim: true); if (exactMatch.Success) { var swift = GetSwiftDay(exactMatch.Groups["day"].Value); var numErs = this.config.IntegerExtractor.Extract(trimmedText); var numOfDays = Convert.ToInt32((double)(this.config.NumberParser.Parse(numErs[0]).Value ?? 0)); var value = referenceDate.AddDays(numOfDays + swift); ret.Timex = DateTimeFormatUtil.LuisDate(value); ret.FutureValue = ret.PastValue = DateObject.MinValue.SafeCreateFromValue(value.Year, value.Month, value.Day); ret.Success = true; return(ret); } // Handle "two sundays from now" exactMatch = this.config.RelativeWeekDayRegex.MatchExact(trimmedText, trim: true); if (exactMatch.Success) { var numErs = this.config.IntegerExtractor.Extract(trimmedText); var num = Convert.ToInt32((double)(this.config.NumberParser.Parse(numErs[0]).Value ?? 0)); var weekdayStr = exactMatch.Groups["weekday"].Value; var value = referenceDate; // Check whether the determined day of this week has passed. if (value.DayOfWeek > (DayOfWeek)this.config.DayOfWeek[weekdayStr]) { num--; } while (num-- > 0) { value = value.Next((DayOfWeek)this.config.DayOfWeek[weekdayStr]); } ret.Timex = DateTimeFormatUtil.LuisDate(value); ret.FutureValue = ret.PastValue = DateObject.MinValue.SafeCreateFromValue(value.Year, value.Month, value.Day); ret.Success = true; return(ret); } // Handle "next Sunday", "upcoming Sunday" // We define "upcoming Sunday" as the nearest Sunday to come (not include today) // We define "next Sunday" as Sunday of next week exactMatch = this.config.NextRegex.MatchExact(trimmedText, trim: true); if (exactMatch.Success) { var weekdayStr = exactMatch.Groups["weekday"].Value; var value = referenceDate.Next((DayOfWeek)this.config.DayOfWeek[weekdayStr]); if (this.config.UpcomingPrefixRegex.MatchBegin(trimmedText, trim: true).Success) { value = referenceDate.Upcoming((DayOfWeek)this.config.DayOfWeek[weekdayStr]); } ret.Timex = DateTimeFormatUtil.LuisDate(value); ret.FutureValue = ret.PastValue = DateObject.MinValue.SafeCreateFromValue(value.Year, value.Month, value.Day); ret.Success = true; return(ret); } // Handle "this Friday" exactMatch = this.config.ThisRegex.MatchExact(trimmedText, trim: true); if (exactMatch.Success) { var weekdayStr = exactMatch.Groups["weekday"].Value; var value = referenceDate.This((DayOfWeek)this.config.DayOfWeek[weekdayStr]); ret.Timex = DateTimeFormatUtil.LuisDate(value); ret.FutureValue = ret.PastValue = DateObject.MinValue.SafeCreateFromValue(value.Year, value.Month, value.Day); ret.Success = true; return(ret); } // Handle "last Friday", "last mon" // We define "past Sunday" as the nearest Sunday that has already passed (not include today) // We define "previous Sunday" as Sunday of previous week exactMatch = this.config.LastRegex.MatchExact(trimmedText, trim: true); if (exactMatch.Success) { var weekdayStr = exactMatch.Groups["weekday"].Value; var value = referenceDate.Last((DayOfWeek)this.config.DayOfWeek[weekdayStr]); if (this.config.PastPrefixRegex.MatchBegin(trimmedText, trim: true).Success) { value = referenceDate.Past((DayOfWeek)this.config.DayOfWeek[weekdayStr]); } ret.Timex = DateTimeFormatUtil.LuisDate(value); ret.FutureValue = ret.PastValue = DateObject.MinValue.SafeCreateFromValue(value.Year, value.Month, value.Day); ret.Success = true; return(ret); } // Handle "Friday" exactMatch = this.config.WeekDayRegex.MatchExact(trimmedText, trim: true); if (exactMatch.Success) { var weekdayStr = exactMatch.Groups["weekday"].Value; var weekDay = this.config.DayOfWeek[weekdayStr]; var value = referenceDate.This((DayOfWeek)this.config.DayOfWeek[weekdayStr]); if (weekDay == 0) { weekDay = 7; } if (weekDay < (int)referenceDate.DayOfWeek) { value = referenceDate.Next((DayOfWeek)weekDay); } ret.Timex = "XXXX-WXX-" + weekDay; var futureDate = value; var pastDate = value; if (futureDate < referenceDate) { futureDate = futureDate.AddDays(7); } if (pastDate >= referenceDate) { pastDate = pastDate.AddDays(-7); } ret.FutureValue = DateObject.MinValue.SafeCreateFromValue(futureDate.Year, futureDate.Month, futureDate.Day); ret.PastValue = DateObject.MinValue.SafeCreateFromValue(pastDate.Year, pastDate.Month, pastDate.Day); ret.Success = true; return(ret); } // Handle "for the 27th." match = this.config.ForTheRegex.Match(text); if (match.Success) { int day = 0, month = referenceDate.Month, year = referenceDate.Year; var dayStr = match.Groups["DayOfMonth"].Value; // Create a extract result which content ordinal string of text ExtractResult er = new ExtractResult { Text = dayStr, Start = match.Groups["DayOfMonth"].Index, Length = match.Groups["DayOfMonth"].Length, }; day = Convert.ToInt32((double)(this.config.NumberParser.Parse(er).Value ?? 0)); ret.Timex = DateTimeFormatUtil.LuisDate(-1, -1, day); DateObject futureDate; var tryStr = DateTimeFormatUtil.LuisDate(year, month, day); if (DateObject.TryParse(tryStr, out DateObject _)) { futureDate = DateObject.MinValue.SafeCreateFromValue(year, month, day); } else { futureDate = DateObject.MinValue.SafeCreateFromValue(year, month + 1, day); } ret.FutureValue = futureDate; ret.PastValue = ret.FutureValue; ret.Success = true; return(ret); } // Handling cases like 'Thursday the 21st', which both 'Thursday' and '21st' refer to a same date match = this.config.WeekDayAndDayOfMothRegex.Match(text); if (match.Success) { int month = referenceDate.Month, year = referenceDate.Year; // create a extract result which content ordinal string of text ExtractResult extractResultTmp = new ExtractResult { Text = match.Groups["DayOfMonth"].Value, Start = match.Groups["DayOfMonth"].Index, Length = match.Groups["DayOfMonth"].Length, }; // parse the day in text into number var day = Convert.ToInt32((double)(this.config.NumberParser.Parse(extractResultTmp).Value ?? 0)); // The validity of the phrase is guaranteed in the Date Extractor ret.Timex = DateTimeFormatUtil.LuisDate(year, month, day); ret.FutureValue = new DateObject(year, month, day); ret.PastValue = new DateObject(year, month, day); ret.Success = true; return(ret); } // Handling cases like 'Monday 21', which both 'Monday' and '21' refer to the same date. // The year of expected date can be different to the year of referenceDate. match = this.config.WeekDayAndDayRegex.Match(text); if (match.Success) { int month = referenceDate.Month, year = referenceDate.Year; // Create a extract result which content ordinal string of text ExtractResult ertmp = new ExtractResult { Text = match.Groups["day"].Value, Start = match.Groups["day"].Index, Length = match.Groups["day"].Length, }; // Parse the day in text into number var day = Convert.ToInt32((double)(this.config.NumberParser.Parse(ertmp).Value ?? 0)); // Firstly, find a latest date with the "day" as pivotDate. // Secondly, if the pivotDate equals the referenced date, in other word, the day of the referenced date is exactly the "day". // In this way, check if the pivotDate is the weekday. If so, then the futureDate and the previousDate are the same date (referenced date). // Otherwise, increase the pivotDate month by month to find the latest futureDate and decrease the pivotDate month // by month to the latest previousDate. // Notice: if the "day" is larger than 28, some months should be ignored in the increase or decrease procedure. var pivotDate = new DateObject(year, month, 1); var daysInMonth = DateObject.DaysInMonth(year, month); if (daysInMonth >= day) { pivotDate = DateObject.MinValue.SafeCreateFromValue(year, month, day); } else { // Add 1 month is enough, since 1, 3, 5, 7, 8, 10, 12 months has 31 days pivotDate = pivotDate.AddMonths(1); pivotDate = DateObject.MinValue.SafeCreateFromValue(pivotDate.Year, pivotDate.Month, day); } var numWeekDayInt = (int)pivotDate.DayOfWeek; var extractedWeekDayStr = match.Groups["weekday"].Value; var weekDay = this.config.DayOfWeek[extractedWeekDayStr]; if (!pivotDate.Equals(DateObject.MinValue)) { if (day == referenceDate.Day && numWeekDayInt == weekDay) { // The referenceDate is the weekday and with the "day". ret.FutureValue = new DateObject(year, month, day); ret.PastValue = new DateObject(year, month, day); ret.Timex = DateTimeFormatUtil.LuisDate(year, month, day); } else { var futureDate = pivotDate; var pastDate = pivotDate; while ((int)futureDate.DayOfWeek != weekDay || futureDate.Day != day || futureDate < referenceDate) { // Increase the futureDate month by month to find the expected date (the "day" is the weekday) and // make sure the futureDate not less than the referenceDate. futureDate = futureDate.AddMonths(1); var tmp = DateObject.DaysInMonth(futureDate.Year, futureDate.Month); if (tmp >= day) { // For months like January 31, after add 1 month, February 31 won't be returned, so the day should be revised ASAP. futureDate = futureDate.SafeCreateFromValue(futureDate.Year, futureDate.Month, day); } } ret.FutureValue = futureDate; while ((int)pastDate.DayOfWeek != weekDay || pastDate.Day != day || pastDate > referenceDate) { // Decrease the pastDate month by month to find the expected date (the "day" is the weekday) and // make sure the pastDate not larger than the referenceDate. pastDate = pastDate.AddMonths(-1); var tmp = DateObject.DaysInMonth(pastDate.Year, pastDate.Month); if (tmp >= day) { // For months like March 31, after minus 1 month, February 31 won't be returned, so the day should be revised ASAP. pastDate = pastDate.SafeCreateFromValue(pastDate.Year, pastDate.Month, day); } } ret.PastValue = pastDate; if (weekDay == 0) { weekDay = 7; } ret.Timex = "XXXX-WXX-" + weekDay; } } ret.Success = true; return(ret); } return(ret); }
private DateTimeResolutionResult ParseDuration(string text, DateObject referenceDate) { var ret = new DateTimeResolutionResult(); DateObject beginDate; var endDate = beginDate = referenceDate; string timex = string.Empty; bool restNowSunday = false; var ers = config.DurationExtractor.Extract(text, referenceDate); if (ers.Count == 1) { var pr = config.DurationParser.Parse(ers[0]); var beforeStr = text.Substring(0, pr.Start ?? 0).Trim().ToLowerInvariant(); var afterStr = text.Substring((pr.Start ?? 0) + (pr.Length ?? 0)).Trim().ToLowerInvariant(); var mod = ""; if (pr.Value != null) { var durationResult = (DateTimeResolutionResult)pr.Value; if (string.IsNullOrEmpty(durationResult.Timex)) { return(ret); } var prefixMatch = config.PastRegex.Match(beforeStr); if (prefixMatch.Success) { mod = TimeTypeConstants.beforeMod; beginDate = DurationParsingUtil.ShiftDateTime(durationResult.Timex, endDate, false); } else { var suffixMatch = config.PastRegex.Match(afterStr); if (suffixMatch.Success) { mod = TimeTypeConstants.beforeMod; beginDate = DurationParsingUtil.ShiftDateTime(durationResult.Timex, endDate, false); } } prefixMatch = config.FutureRegex.Match(beforeStr); if (prefixMatch.Success && prefixMatch.Length == beforeStr.Length) { mod = TimeTypeConstants.afterMod; // For future the beginDate should add 1 first beginDate = referenceDate.AddDays(1); endDate = DurationParsingUtil.ShiftDateTime(durationResult.Timex, beginDate, true); } // Handle the "in two weeks" case which means the second week prefixMatch = config.InConnectorRegex.Match(beforeStr); if (prefixMatch.Success && prefixMatch.Length == beforeStr.Length && !DurationParsingUtil.IsMultipleDuration(durationResult.Timex)) { mod = TimeTypeConstants.afterMod; beginDate = referenceDate.AddDays(1); endDate = DurationParsingUtil.ShiftDateTime(durationResult.Timex, beginDate, true); // Change the duration value and the beginDate var unit = durationResult.Timex.Substring(durationResult.Timex.Length - 1); durationResult.Timex = "P1" + unit; beginDate = DurationParsingUtil.ShiftDateTime(durationResult.Timex, endDate, false); } if (!string.IsNullOrEmpty(mod)) { ((DateTimeResolutionResult)pr.Value).Mod = mod; } timex = durationResult.Timex; ret.SubDateTimeEntities = new List <object> { pr }; } } // Parse "rest of" var match = this.config.RestOfDateRegex.Match(text); if (match.Success) { var durationStr = match.Groups["duration"].Value; var durationUnit = this.config.UnitMap[durationStr]; switch (durationUnit) { case "W": var diff = 7 - (((int)beginDate.DayOfWeek) == 0? 7: (int)beginDate.DayOfWeek); endDate = beginDate.AddDays(diff); timex = "P" + diff + "D"; if (diff == 0) { restNowSunday = true; } break; case "MON": endDate = DateObject.MinValue.SafeCreateFromValue(beginDate.Year, beginDate.Month, 1); endDate = endDate.AddMonths(1).AddDays(-1); diff = endDate.Day - beginDate.Day + 1; timex = "P" + diff + "D"; break; case "Y": endDate = DateObject.MinValue.SafeCreateFromValue(beginDate.Year, 12, 1); endDate = endDate.AddMonths(1).AddDays(-1); diff = endDate.DayOfYear - beginDate.DayOfYear + 1; timex = "P" + diff + "D"; break; } } if (!beginDate.Equals(endDate) || restNowSunday) { endDate = InclusiveEndPeriod ? endDate.AddDays(-1) : endDate; ret.Timex = $"({FormatUtil.LuisDate(beginDate)},{FormatUtil.LuisDate(endDate)},{timex})"; ret.FutureValue = ret.PastValue = new Tuple <DateObject, DateObject>(beginDate, endDate); ret.Success = true; return(ret); } return(ret); }
private void vCarregaDadosDefault(ref mdlDataBaseAccess.Tabelas.XsdTbSaques.tbSaquesRow dtrwSaque) { // Idioma int nIdIdioma = 3; if (!dtrwSaque.IsnIdIdiomaNull()) { nIdIdioma = dtrwSaque.nIdIdioma; } System.Windows.Forms.ImageList ilBandeiras = null; mdlEsquemaPagamento.clsEsquemaPagamento objEsq = new mdlEsquemaPagamento.clsEsquemaPagamentoFaturaComercial(ref m_cls_ter_tratadorErro, ref m_cls_dba_ConnectionDB, m_strEnderecoExecutavel, ref ilBandeiras, m_nIdExportador, m_strIdPE); System.Text.StringBuilder strbData = new System.Text.StringBuilder(); if ((objEsq.CondicaoAvista) > 0) { switch (nIdIdioma) { case (int)mdlConstantes.Idioma.Portugues: strbData.Append("A Vista"); break; case (int)mdlConstantes.Idioma.Ingles: strbData.Append("At Sight"); break; } } if (((objEsq.CondicaoPostecipado) > 0) && (objEsq.PostecipadoCondicao != mdlEsquemaPagamento.DocumentoCondicao.Aceite)) { System.DateTime dtData = System.DateTime.Now; string strFormato = "dd/MMM/yyyy"; switch (objEsq.PostecipadoCondicao) { case mdlEsquemaPagamento.DocumentoCondicao.Conhecimento: mdlData.clsData objDataConhecimento = new mdlData.DataEmbarque.Faturas.clsDataEmbarqueComercial(ref m_cls_ter_tratadorErro, ref m_cls_dba_ConnectionDB, m_strEnderecoExecutavel, m_nIdExportador, m_strIdPE); dtData = objDataConhecimento.Data; if (dtData.Equals(mdlConstantes.clsConstantes.DATANULA)) { m_strDataDefault = ""; return; } break; case mdlEsquemaPagamento.DocumentoCondicao.Fatura: mdlData.clsData objData = new mdlData.DataEmissao.Faturas.clsDataEmissaoComercial(ref m_cls_ter_tratadorErro, ref m_cls_dba_ConnectionDB, m_strEnderecoExecutavel, m_nIdExportador, m_strIdPE); dtData = objData.Data; break; case mdlEsquemaPagamento.DocumentoCondicao.Saque: if (!dtrwSaque.IsdtDataEmissaoNull()) { dtData = dtrwSaque.dtDataEmissao; } break; } vIncrementaData(ref dtData, objEsq.PostecipadoUnidadeTempo, objEsq.PostecipadoQuantTempo); if (strbData.Length != 0) { strbData.Append(" , "); } strbData.Append(dtData.ToString(strFormato)); for (int i = 1; i < objEsq.PostecipadoQuantidadeParcelas; i++) { vIncrementaData(ref dtData, objEsq.PostecipadoUnidadeTempo, objEsq.PostecipadoIntervalo); strbData.Append(" , "); strbData.Append(dtData.ToString(strFormato)); } } m_strDataDefault = strbData.ToString(); }
public Order(int id, string customerid, int employeeid, DateTime orderdate, DateTime requireddate, DateTime shippeddate, int shipvia, double freight, string shipname, string shipaddress, string shipcity, string shiparegion, string shippostalcode, string shipcountry, List<OrderDetails> details) { ID = id; CustomerID = customerid; EmployeeID = employeeid; OrderDate = orderdate; RequiredDate = requireddate; ShippedDate = shippeddate; ShipVia = shipvia; Freight = freight; ShipName = shipname; ShipAddress = shipaddress; ShipCity = shipcity; ShipRegion = shiparegion; ShipPostalCode = shippostalcode; ShipCountry = shipcountry; Details = details; if (orderdate.Equals(DateTime.MinValue)) Status = OrderStatus.NEW; else if (ShippedDate.Equals(DateTime.MinValue)) Status = OrderStatus.NOTSHIPPED; else Status = OrderStatus.SHIPPED; }