[英]sql datetime to compare with string
if i have the following to access an sql database for a date to compare it to a string that a user enters: 如果我具有以下访问sql数据库的日期,以将其与用户输入的字符串进行比较:
public IQueryable<Audit> FindAllAuditsByNameDate(String name, String date)
{
return from audit in db.Audits
where audit.EventTime.ToString().Contains(date) && audit.User.UserName.Contains(name)
orderby audit.User.UserName
select audit;
}
it fails is the user enters the "/" character in a date. 如果用户在日期中输入“ /”字符,它将失败。 how do i work around this?
我该如何解决?
Try DateTime.Parse
. 尝试
DateTime.Parse
。 It's able to understand a lot of the common formats for entering DateTimes. 它能够理解许多用于输入DateTimes的常见格式。
DateTime dateStart = DateTime.Parse(date);
DateTime dateEnd = dateStart.AddDays(1);
return from audit in db.Audits
where audit.EventTime >= dateStart &&
audit.EventTime < dateEnd &&
audit.User.UserName.Contains(name)
orderby audit.User.UserName
select audit;
If DateTime.Parse
doesn't parse the format you want, you can always use DateTime.ParseExact
and provide your own format strings. 如果
DateTime.Parse
没有解析所需的格式,则可以始终使用DateTime.ParseExact
并提供自己的格式字符串。
Considering EventTime is of type DateTime? 考虑到EventTime是DateTime类型的吗? you need to check it against its value.
您需要对照其值进行检查。 First convert the string date to DateTime
首先将字符串日期转换为DateTime
DateTime newDate = Convert.ToDateTime(date);
return from audit in db.Audits
where audit.EventTime.Value == newDate && audit.User.UserName.Contains(name)
orderby audit.User.UserName
select audit;
Warning - Don't use Contains
. 警告-请勿使用
Contains
。
Suppose I have two list objects. 假设我有两个列表对象。
List 1 List 2
1 12
2 7
3 8
4 98
5 9
6 10
7 6
public IQueryable<Audit> FindAllAuditsByNameDate(String name, String date)
{
DateTime Dt;
if (DateTime.TryParse(date, out Dt))
{
return from audit in db.Audits
where audit.EventTime.ToString().Contains(date) && audit.User.UserName.Contains(name)
orderby audit.User.UserName
select audit;
}
return null;
}
- Returns a bool indicating whether it succeeded.
返回一个布尔值,指示它是否成功。
- It just try/catch internally that why is implemented without exceptions so that it is fast.
它只是在内部尝试/捕获为什么没有例外的实现,因此速度很快。
- Use it in case the value may be InValid.
如果值可能是InValid,请使用它。
- Throws an exception.
引发异常。
- Use it if you are sure the value will be valid
如果您确定该值将有效,请使用它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.