The handling method that failed to convert the LINQ string to datetime

  • 2020-05-30 19:50:08
  • OfStack

Today, when using LINQ, since the time saved in the database is in varchar() format, it is necessary to compare the time order when querying, so it USES:

from j in system.jhzd
where j.dwbm.ToString().Trim() == branchcode.ToString().Trim()
&& Convert.ToDateTime(j.yearmonth.ToString().Trim()).CompareTo(Convert.ToDateTime(timeFrom)) >= 0
&& Convert.ToDateTime(j.yearmonth.ToString().Trim()).CompareTo(Convert.ToDateTime(timeTo)) <= 0
join b in system.t_sys_Branch
on j.dwbm.ToString().Trim() equals b.BranchCode
join c in system.T_CWLB
on j.xmlb.ToString().Trim() equals c.ID
select new
BranchName = b.BranchName,
category = c.CWMC,
money =,
comefrom = j.zjly,
time = j.yearmonth,
zhaiyao = j.zhaiyao,

However, the database report "failed to convert from string to datetime" was found when used.

I tried a lot of things, but it didn't work. Finally, I found that the string in the yearmonth field in the database was "January 04, 2013".

When you change it to "2013-01-04", the query is found to be normal and valid.

Related articles: