Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Query to Convert string to datetime

I want to convert the string value to date time

Class

public class demoDate
{
    public DateTime DueDate;
    public int OrderReportID;

    public DateTime _DueDate 
    { 
        get { return DueDate; } 
        set { DueDate = value; } 
    }

    public int _OrderReportID 
    { 
        get { return OrderReportID; } 
        set { OrderReportID = value;} 
    }
}

Query

var DateQuery = (from o in db.Order_Reports
                 select new demoDate {
                    DueDate = System.DateTime.Parse(o.ReportDueDateTime), 
                    OrderReportID = o.OrderReportID
                 }).ToList();

This coding shows following error

LINQ to Entities does not recognize the method 'System.DateTime Parse(System.String)' method, and this method cannot be translated into a store expression.

like image 978
Golda Avatar asked Jan 10 '14 08:01

Golda


People also ask

How to convert string to DateTime in linq query?

LinqToEntities can convert a string to a datetime (inside the query) This works. You need an Extensionmethod to make the dateTime parsing safe. After that you can use the result of that method in the Linq query.

How to get current Date in linq query?

DateTime todaysDate = DateTime. Now; DateTime yesterdaysDate = DateTime. Now. AddDays(-1); var result = (from a in cxt.


Video Answer


1 Answers

If you need convert it with SQL you can try use SqlFunctions.DateAdd and just add zero interval.

var DateQuery = db.Order_Reports.Select(o => new demoDate {
    DueDate = SqlFunctions.DateAdd("day", 0, o.ReportDueDateTime), 
    OrderReportID = o.OrderReportID
 });
like image 174
Volodymyr Baydalka Avatar answered Oct 11 '22 22:10

Volodymyr Baydalka