locked
How to compare date in EF with a specific format RRS feed

  • Question

  • see my below sql where i have shown how i compare date in specific format. tell me how could i achieve the same kind of sql generate with EF for date comparison ?

    select * from employee
    where convert(varchar,joinDate,112) >= '20151117'

    convert my above sq l to valid EF linq query where date should be compare with a format like yyyyMMdd. thanks

    Thursday, November 17, 2016 2:27 PM

Answers

  • Hi Mou_kolkata,

    We could convert the string to Datetime and compare them. like this:

    string date = "20151117";
    DateTime ddate = DateTime.ParseExact(date, "yyyyMMdd", CultureInfo.InvariantCulture);
    using (var db = new EFDemoContext())
    {
        var query = db.Employees.Where(t => t.joinDate >= ddate);
    }

    In addition, you could use EntityFunctions to achieve it. like this:

     string date = "20151117";
    
                DateTime ddate = DateTime.ParseExact(date, "yyyyMMdd", CultureInfo.InvariantCulture);
    
                using (var db = new EFDemoContext())
                {
                    var query = db.Employees.Where(t => EntityFunctions.DiffDays(ddate, t.joinDate) >=0 );
    }

    Best regards,

    Cole Wu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by Mou_kolkata Friday, November 18, 2016 11:58 AM
    Friday, November 18, 2016 1:48 AM