问题描述:

I have stored data in Sql Server and date is stored in this format 2016-07-25 08:57:03.483 and datatype i given is datetime.

Now i want to filter data from database using date.

string startDate = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");

string endDate = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");

DateTime startDate1 = DateTime.Parse(startDate);

DateTime endDate1 = DateTime.Parse(endDate);

ViewBag.billHistory = db.tbl_electricity.

Where(x.INSRT_TMSP>= startDate1 && x.INSRT_TMSP<= endDate1).ToList();

But data is not filtering What i did wrong ?

网友答案:

If db values content a time part which needs to be ignored, you should compare only date parts as

ViewBag.billHistory = db.tbl_electricity.
Where(x.INSRT_TMSP.Date>= startDate1 && x.INSRT_TMSP.Date<= endDate1).ToList();

See How to compare DateTime without time via LINQ?

If time is never required, simply change the data type in the database from datetime to date.

网友答案:

Create a new DateTime value with the milliseconds component set to 0:

DateTime dt = DateTime.Now;
dt.AddMilliseconds(-dt.Millisecond);

Or you could also use below date format:

string dt= DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff",
                                            CultureInfo.InvariantCulture);
网友答案:

`

Convert your string to universaltime by: string1.value.toUniversalTime() OR string1.toUniversalTime()

like this:

string startDate = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
string endDate = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");
startDate.toUniversalTime();
endDate.toUniversalTime();
DateTime startDate1 = DateTime.Parse(startDate);
DateTime endDate1 = DateTime.Parse(endDate);

ViewBag.billHistory = db.tbl_electricity.
Where(x.INSRT_TMSP>= startDate1 && x.INSRT_TMSP<= endDate1).ToList();

`

相关阅读:
Top