geting-error无法将运算符应用于system.datetime和string类型的操作数
本文关键字:string 类型 操作数 datetime system 运算符 应用于 geting-error | 更新日期: 2023-09-27 18:29:34
我正在使用Linq查询,但出现错误Cannot apply operator >= to operands of type system.datetime and string
这是我的linq查询
var myBirthDate= BirthDate.ToString("yyyy-MM-dd HH':'mm':'ss");
var myList= (from myEntity in myEntityRepository.AsQueryable()
where
myEntity.id== Id &&
myEntity.birthdate >= myBirthDate
select myEntity).Take(1);
我将日期转换为yyyy-MM-dd HH':'mm':'ss
格式,因为我从客户端获得了其他格式。
如何避免此错误?
使用ToString()
方法后将生成字符串,而不是Datetime
var myBirthDate= BirthDate.ToString("yyyy-MM-dd HH':'mm':'ss");
使用DateTime.TryParse从客户端提供的值中获取DateTime。然后在查询中使用它。
如果收到的日期与当前区域性不同,则可以使用DateTime.Parse转换为正确的DateTime变量。
当您使用ToString将DateTime类型转换为格式化的日期字符串时,myBirthDate变量将变为string,因此>=无法按预期工作。
这是一个示例:
using System;
public class Example
{
public static void Main()
{
string[] dateStrings = {"2008-05-01T07:34:42-5:00",
"2008-05-01 7:34:42Z",
"Thu, 01 May 2008 07:34:42 GMT"};
foreach (string dateString in dateStrings)
{
DateTime convertedDate = DateTime.Parse(dateString);
Console.WriteLine("Converted {0} to {1} time {2}",
dateString,
convertedDate.Kind.ToString(),
convertedDate);
}
}
}