【问题标题】:Convert string to datetime value in LINQ在 LINQ 中将字符串转换为日期时间值
【发布时间】:2016-05-16 17:44:26
【问题描述】:
假设我有一个表格以 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); };
但事实证明,ParseExact 函数无法被识别的错误。
【问题讨论】:
标签:
c#
sql-server
linq-to-sql
【解决方案1】:
可能值得通过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));
初始选择是为了确保仅获取相关列,而不是整个实体(仅用于丢弃大部分实体)。我也避免使用匿名类型,因为这里似乎没有意义。
注意我是如何指定不变的文化的——你几乎可以肯定不只想使用当前的文化。而且我更改了用于解析的模式,因为听起来您的 source 数据是 yyyyMMdd 格式。
当然,如果可能的话,您应该更改数据库架构以将日期值存储在基于日期的列中,而不是作为文本。
【解决方案2】:
如前所述,最好将日期作为日期类型列存储在数据库中,但如果您只想将字符串从一种格式转换为另一种格式,您可以这样做:
db.tb1.Select(x => String.Format("{0}/{1}/{2}", x.Substring(6, 2), x.Substring(4, 2), x.Substring(0, 4))
【解决方案3】:
在 SQL Server 中创建一个 UDF,然后导入到您的 linq to 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))