locked
Compare date in specific format in LINQ RRS feed

  • Question

  • User264732274 posted

    i often compare date this way by in-line sql.

    SELECT * FROM dbo.tbl_MyTable
    WHERE
    CONVERT(VARCHAR, DateTimeValueColumn, 112) >= CONVERT(VARCHAR, '20150101', 112) AND
    CONVERT(VARCHAR, DateTimeValueColumn, 112) <= CONVERT(VARCHAR, '20150201', 112)

    how could i instruct LINQ to generate the above SQL for date comparison. looking for sample code to achieve this. thanks

    Thursday, April 2, 2015 4:16 AM

Answers

  • User-824764785 posted

    Convert(VARCHAR, DateTimeValueColumn, 112) basically returns a string only with date so in LINQ we can use Date property of DateTime class, like DateTime.Now.Date:

    var db = new SqlDataContext();
    
    var dateToCompare = new DateTime(2015, 01, 31).Date;
    
    var result = db.tbl_MyTables.Where(x=> x.DateTimeValueColumn.Date >= dateToCompare && x.DateTimeValueColumn.Date <= dateToCompare);

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, April 2, 2015 5:08 AM