問題描述
假設我有一個表,以 String 格式存儲日期時間 (yyyyMMdd) 列表.我如何提取它們并將它們轉換為日期時間格式 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函數無法識別的錯誤.
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.
順便說一下,請注意我是如何指定不變文化的 - 您幾乎肯定不想只想使用當前文化.我更改了用于解析的模式,因為聽起來您的 source 數據采用 yyyyMMdd
格式.
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 中將字符串轉換為日期時間值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!