Convert string to datetime value in LINQ

前端 未结 3 460
北恋
北恋 2020-12-20 01:42

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 ?

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-20 02:42

    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.

提交回复
热议问题