LINQ Convert string to datetime
In SQL I do it 开发者_运维问答like this:
DateMonth=convert(datetime, convert(char(6), AASI.Inv_Acctcur) + '01')
How to do it in LINQ? String is in following format:
"yyyyMMdd"
Thanks,
IleEDIT:
Example of SQL usage:
SELECT convert(datetime, '20161023', 112) -- yyyymmdd
Found here: http://www.sqlusa.com/bestpractices/datetimeconversion/
This page on MSDN documentation lists all convert methods that LINQ to SQL
does not support.
Convert.ToDateTime
is not listed in there. So, I guess you could just use Convert.ToDateTime
to do what you want.
This is not something typically for LINQ or any LINQ over Expression trees enabled provider (such as LINQ to SQL, LINQ to Entities, LINQ to NHibernate, LLBLGen Pro, etc, etc). This is simply a language question. You want to know how to convert the format yyyyMMdd to a DateTime
.
The trick is to leave the conversion OUT of your LINQ (over Expression trees) query, because a LINQ provider will not be able to convert it, or if it can, you will get very provider specific implementation.
Therefore, the trick is to get it out of the database as a string (or of course even better: change your database model) and convert it to a DateTime
in .NET. For instance:
// Doing .ToArray is essential, to ensure that the
// query is executed right away.
string[] inMemoryCollectionStrings = (
from item in db.Items
where some_condition
select item.Inv_Acctcur).ToArray();
// This next query does the translation from string to DateTime.
IEnumerable<DateTime> dates =
from value in inMemoryCollectionStrings
select DateTime.ParseExact(value, "yyyyMMdd",
CultureInfo.InvariantCulture);
In other words, you can use the following line to make the conversion:
DateTime.ParseExact(value, "yyyyMMdd", CultureInfo.InvariantCulture);
精彩评论