DateTime format with Entity Framework

c# datetime entity-framework

Question

Who can describe how it operates? In SQL Server, I must compare a DateTime with user input.

Here is an illustration of what I'm after:

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. 
Console.Read();

Entity Framework is what I'm using, and in the entity classDates the properties are DateTime, and I need to compare those with user input. The CreateDate function was the only thing that worked.

As you are aware, I am unable to directly compare the POST value to a Date attribute. Example:

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

I therefore attempted to convert 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? So, the result ofstart_date is:

2012-02-13 12:00:00 am

However, the end and start dates in the database are as follows:

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

When the input date is in, how can I compare the date?2012-02-13 00:00:00.000 format?

I just need the same format and data type, regardless of what you choose to employ.

1
3
8/13/2018 10:33:37 PM

Popular Answer

i just need the same format

Not at all, no. You require the best data type, which isDateTime (Or perhapsDateTimeOffset ) and you must disregard string formatting.

A alternate textual representation of the value is "2012-02-13 12:00:00 am," which can also be written as "2012-02-13 00:00:00.000." Both signify 12:01 a.m. on February 13, 2012. Providing your database field is a suitableDateTime kind, it really shouldn't matter. You don't need to be concerned with format, really.

Whether the values are in UTC or local time is something you should be concerned about, but it is an other issue.

Personally, I'd utilizeDateTime.Parse or DateTime.ParseExact instead ofConvert.ToDateTime , although that's a little bit different.)

4
4/8/2013 3:11:09 PM


Related Questions





Related

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