在LINQ中将字符串转换为datetime值

假设我有一个表以String格式存储日期时间列表(yyyyMMdd)。 我如何提取它们并将它们转换为DateTime格式dd / MM / yyyy?

例如20120101 – > 01/01/2012

我尝试过以下方法:

var query = from tb in db.tb1 select new { dtNew = DateTime.ParseExact(tb.dt, "dd/MM/yyyy", null); }; 

但事实certificate错误说ParseExact函数不能被复原。

通过AsEnumerable本地解析而不是在数据库中进行解析可能是值得的:

 var query = db.tb1.Select(tb => tb.dt) .AsEnumerable() // Do the rest of the processing locally .Select(x => DateTime.ParseExact(x, "yyyyMMdd", CultureInfo.InvariantCulture)); 

初始选择是确保仅提取相关列,而不是整个实体(仅用于大部分要丢弃)。 我也避免使用匿名类型,因为这里似乎没有任何意义。

请注意我是如何指定不变文化的 – 你几乎肯定不想只使用当前的文化。 我已经改变了用于解析的模式,因为它听起来像你的数据是yyyyMMdd格式。

当然,如果可能的话,您应该更改数据库模式以将日期值存储在基于日期的列中,而不是文本中。

如前所述,最好将日期存储为数据库中的日期类型列,但如果只想将字符串从一种格式转换为另一种格式,则可以执行以下操作:

 db.tb1.Select(x => String.Format("{0}/{1}/{2}", x.Substring(6, 2), x.Substring(4, 2), x.Substring(0, 4)) 

在SQL Server中创建一个UDF,然后导入到linq到sql项目并在比较中使用

 -- ============================================= -- Author: -- Create date: -- Description: Convert varchar to date -- SELECT dbo.VarCharAsDate('11 May 2016 09:00') -- ============================================= CREATE FUNCTION VarCharAsDate ( -- Add the parameters for the function here @DateAsVarchar NVarchar(100) ) RETURNS DateTime AS BEGIN -- Declare the return variable here if IsDate(@DateAsVarchar) = 1 BEGIN -- Return the result of the function RETURN convert(datetime, @DateAsVarchar, 109) END RETURN NULL END GO 

然后在代码中

 .Where(p => ValueDateTime > db.VarCharAsDate(p.Value))