简体   繁体   中英

LINQ - Convert String to Datetime

as follow my problem:

I have a table with all nvarchar columns and I would like to load only the records from the current day, like below:

 var query = from item in dataContext.Items
             orderby item.CDATE_IUD descending
             where item.QV_USER == user
             where item.QV_EXT == ext
             where item.ACTIVE == 1
             where DbFunctions.DiffDays(Convert.ToDateTime(item.CDATE_IUD), DateTime.Now.Date) == 0
             select item;

I get an error that ToDateTime is not recognized in LINQ.

My desired output:

  • Load only the current day records

Input:

  • item.CDATE_IUD is a string and has the following format dd.mm.yyyy hh:mm:ss (eg 20.07.2015 16:12:48)

Any help would be appreciated.

Update:

This works for me:

 string today = DateTime.Now.ToString("dd.MM.yyyy");
 var query = from item in dataContext.Items
             orderby item.CDATE_IUD descending
             where item.QV_USER == user
             where item.QV_EXT == ext
             where item.ACTIVE == 1
             where item.CDATE_IUD.Substring(0,10) == today
             select item;

I'm assuming item.CDATE_IUD is a string representation of a date.

Linq to EF and Linq to SQL do not support string to date conversions. You can do the conversion in memory, but since you're filtering on the parsed value, then you're pulling in ALL records. You might be able to use a string comparison instead:

string today = DateTime.Today.ToString("yyyy-mm-dd"); // or whatever format your DB string is on.
var query = from item in dataContext.Items
                        orderby item.CDATE_IUD descending
                        where item.QV_USER == user
                        where item.QV_EXT == ext
                        where item.ACTIVE == 1
                        where item.CDATE_IUD.StartsWith(today)
                        select item;
DateTime.ParseExact(x, "yyyyMMdd",cultureInfo.InvariantCulture) 

将有助于转换dateTime中的字符串

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM