字符串转换为在LINQ日期时间值 [英] Convert string to datetime value in LINQ
问题描述
假设我有一个表,用于存储日期时间(年月日)在字符串格式的明细表。
我怎么能提取它们并将它们转换成DateTime格式DD / MM / YYYY?
Suppose I have a table storing a list of datetime (yyyyMMdd) in String format. How could I extract them and convert them into DateTime format dd/MM/yyyy ?
例如。 20120101 - > 01/01/2012
e.g. 20120101 -> 01/01/2012
我曾尝试以下内容:
var query = from tb in db.tb1 select new { dtNew = DateTime.ParseExact(tb.dt, "dd/MM/yyyy", null); };
但事实证明,错误说,ParseExact功能不能recgonized。
But it turns out the error saying that the ParseExact function cannot be recgonized.
推荐答案
这是在数据库中可能是值得只是在做解析本地而不是通过 AsEnumerable
:
It's probably worth just doing the parsing locally instead of in the database, via 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));
的初始选择是,以确保只有相关的列被取出,而不是整个实体(仅对于大部分被丢弃)。 。我已经因为似乎没有一点在这里使用匿名类型也避免
The initial select is to ensure that only the relevant column is fetched, rather than the whole entity (only for most of it to be discarded). I've also avoided using an anonymous type as there seems to be no point to it here.
请注意,我是如何的方式指定固定区域性的 - 你几乎肯定的不的希望只使用目前的文化。我已经改变了用于解析的模式,因为它听起来像你的源的数据是年月日
格式。
Note how I've specified the invariant culture by the way - you almost certainly don't want to just use the current culture. And I've changed the pattern used for parsing, as it sounds like your source data is in yyyyMMdd
format.
当然,如果可能的话,你应该改变数据库架构来存储数据在一个基于日期栏,而不是文本。
Of course, if at all possible you should change the database schema to store date values in a date-based column, rather than as text.
这篇关于字符串转换为在LINQ日期时间值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!