DateTime format with Entity Framework

c# datetime entity-framework


Can someone explain how it works? I need compare a DateTime in SQL Server with an user input.

Here an example of what I'm looking for:

DateTime[] dates = { DateTime.Now, DateTime.UtcNow };
Console.WriteLine(dates.Where(x => x < DateTime.Now));    // I need to know if they are the same without converting them to strings. 

I'm using Entity Framework and in the entity class Dates, the attributes are DateTime and I need to compare that with a user's input, and the only solution I found was the CreateDate function.

As you know, I cannot compare the POST value directly with a Date attribute. Example:

db.dates.Where(x => x.StartDate < "2012-02-13 00:00:00.000")    // error, cannot compare DateTime with string

So, I tried converting the value to DateTime:

DateTime start_date = Convert.ToDateTime("2012-02-13 00:00:00.000");
db.dates.Where(x => x.StartDate < start_date )    // PROBLEM!!

Why? Well, the output of start_date is:

2012-02-13 12:00:00 am

But in the database, the end and start date are as follows:

2012-02-13 00:00:00.000    // all have zeros at the end

How can I compare the date when the input date is in 2012-02-13 00:00:00.000 format?

I don't care what to use, I just need the same format and the same data type.

8/13/2018 10:33:37 PM

Popular Answer

i just need the same format

No, you don't. You need the most appropriate data type, which is DateTime (or maybe DateTimeOffset) and you need to forget about the string format.

"2012-02-13 12:00:00 am" is just a different textual representation of the value which can also be represented as "2012-02-13 00:00:00.000". Both represent midnight on February 13th 2012. So long as your database field is an appropriate DateTime type, it shouldn't matter at all. You really don't need to worry about format.

You may need to worry about whether the values are in UTC or local time, but that's a separate matter.

(I'd personally use DateTime.Parse or DateTime.ParseExact rather than Convert.ToDateTime, but that's a slightly different matter.)

4/8/2013 3:11:09 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow