How to convert string to datetime and then get the lowest date - c#

Records are coming from database and date is in the string format. I am using LINQ Min() query to select the record with lowest date. LINQ is not allowing me to use Convert.ToDateTime().
How can I get lowest date record?

You could do something like
.Min(ob => System.Convert.ToDateTime(ob.DateProperty));
This way the value gets converted before checking for the lowest value.

What do you mean by "linq is not allowing me Convert.ToDateTime()" ?
Can you not do:
DateTime minDate = listOfStrings.Select(x => Convert.ToDateTime(x)).Min();
..?
If the strings are not in a date/time format that is handled by Convert.ToDateTime(), you may need to look into DateTime.ParseExact() with an appropriate format string.
Edit: sorry, just realized another possibility. Do you mean that you cannot do the Convert.ToDateTime() because you are using LINQ against SQL and it is not usable within the expression? If so, try:
DateTime minDate = listOfStrings.ToList().Select(x => Convert.ToDateTime(x)).Min();
.. with a ToList() to force it to perform the query and then to the conversion.

there's a way of doing it by using the Orderby method in your LINQ request,
using a Func() on the (datetime)field you wish to order by, then selecting the first element.
It's not very clean as i would use a datetime in the database, but it should work.

Looking into some code samples would be useful. But this might help.
var minDateTime = strings.Min(s => DateTime.Parse(s));

Related

"Where" clause in linq to sql query using DateTime?

I'm trying to run a query of a table with the columns Domain, LastUsed, and FreqInHours In c#.
I just want to return all the Domains that I need to crawl.I find this out by checking the datetime that they were last Crawled (LastUsed) and how frequently they should be crawled (ex. every 6 hours). If the current date/time - the time it was last crawled is greater than the frequency I add want to return that domain.
Here is the current query I've written:
var query = (from c in context.SitemapFreqs
where (DateTime.Now - c.LastUsed).TotalHours > c.Freq
select c.domain);
Here is the exception I'm being given:
LINQ to Entities does not recognize the method 'System.DateTime ?
ToDateTime(System.Object)' method, and this method cannot be translated into a store expression.
Any help would be really appreciated.
You can use DbFunctions class and method DiffHours.
Here is an example:
var query = (from c in context.SitemapFreqs
where DbFunctions.DiffHours(DateTime.Now,c.LastUsed) > c.Freq
select c.domain);
Here is the documentation. Hope it helps.
Complex DateTime stuff is a bit much for Linq2SQL to handle.
If it's a relatively small amount of data, load it all into memory first:
var query = (from c in context.SitemapFreqs.ToList()
where (DateTime.Now - c.LastUsed).TotalHours > c.Freq
select c.domain);
If it's a larger amount of data, you can use DbFunctions, or provide the query yourself.
context.SitemapFreqs.SqlQuery("SELECT * from SitemapFreqs WHERE DATEDIFF('hour', GETDATE(), LastUsed) > Freq")
If you make sure the query returns the columns the SitemapFreqs object expects, it will map the objects just like it would anything else.
Looks like your c.LastUsed property is nullable. You can subtract nullable DateTimes using the c.LastUsed.Value property, but you should know that if it is null, this will throw an exception as you can't subtract a DateTime - null. I believe you have two options:
Change the property LastUsed in your class to a non-nullable DateTime by removing the ?.
Create a method inside of your class that determines if the DateTime? LastUsed is equal to null. If it is, return something where your LINQ query will ignore that value. (I.E: Set the value of LastUsed = DateTime.Now so that your LINQ query comes back as 0).
Hope this helps.

Is there a way to get the long value from a Date in a Linq to Entity query?

First and foremost, yes, I know questions similar to this one have been asked ad nauseam. They typically need to compare two date times.
In my case, I am not trying to compare datetimes. I am trying to perform a mathematical operation which includes a Date property on the entity in the calculation.
I've been looking through the EntityFunctions, but unless I am mistaken, there doesn't seem to be a method that translates Dates to long/int values. Essentially the Ticks property, which Linq to Entities obviously doesn't support.
Is this possible?
For an easy example as to what I am trying to achieve:
var foos = db.Foos.OrderBy(f => f.Score / f.SomeDate.ToLong()).ToList();
If it helps, I'm using code first and the Dates I am referring to are represented by DateTime objects in C#.
you could try others functions to get an Int/Long value like
EntityFunctions.DiffSeconds(fixedDate, f.SomeDate)
Or
EntityFunctions.DiffNanoseconds(fixedDate, f.SomeDate)

How to use ToShortDateString in linq lambda expression?

I need to call ToShortDateString in a linq query suing lambda expressions:
toRet.Notification = Repositories
.portalDb.portal_notifications.OrderByDescending(p => p.id)
.FirstOrDefault(p => p.date.ToShortDateString() == shortDateString);
but I get the error:
An exception of type 'System.NotSupportedException' occurred in
System.Data.Entity.dll but was not handled in user code
Additional information: LINQ to Entities does not recognize the method
'System.String ToShortDateString()' method, and this method cannot be
translated into a store expression.
What can I do, considering that I do need to use ToShortDateString() ?
Thanks.
Linq to Entities cannot convert ToSortDateString method into SQL code. You can't call it on server side. Either move filtering to client side (that will transfer all data from server to client), or consider to use server-side functions to take date part of date (you should pass DateTime object instead of shortDateString):
EntityFunctions.TruncateTime(p.date) == dateWithoutTime
You shouldn't be forcing a string comparison when what you're working with is Date/time data - as soon as you force string comparisons, you're suddenly having to deal with how the strings are formatted.
Instead, have something like:
var endDate = targetDate.AddDays(1);
toRet.Notification = Repositories
.portalDb.portal_notifications.OrderByDescending(p => p.id)
.FirstOrDefault(p => p.date >= targetDate && p.date < endDate);
(Assuming that targetDate is whatever DateTime variable you had that was used to produce shortDateString in your code, and is already a DateTime with no time value)
Try this,
You can also used with below code.
Activity = String.Format("{0} {1}", String.Format("{0:dd-MMM-yyyy}", s.SLIDESHEETDATE), String.Format("{0:HH:mm}", s.ENDDATETIME))
ToShortDateString() method usually used to work only with date and ignore time stamps.
You will get exactly today result-set by using the following query.
Repositories.portalDb.portal_notifications.OrderByDescending(p => p.id)
.FirstOrDefault(p => p.date.Date == DateTime.Now.Date);
By using Date property of DateTime struct you can just fetch record of that date only.
Note: Linq to Objects. Only works if you CAN (or have option) to bypass ToShortDateString() method

Linq to SQL DateTime2 query

I have a table with a datetime2 field and I need to get all rows out of it where the date is today. Rather oddly (in my opinion but I'm sure there's a valid reason for it) if I do:
MyTable.Where(t => t.Date == DateTime.Today).ToList()
it returns nothing even though there are entires with todays date.
What am I missing here? I thought that datetime2 allowed you to query like this instead of having to use greater than and less than to specify a timeframe?
Edit
I've tried using the .Date portion of the DateTime2 representation in Linq to SQL:
MyTable.Where(t => t.Date.Date == DateTime.Today).ToList()
but I'm still getting nothing. Yet in my database there are rows with the value 2011-08-05 00:00:00.0000000 which is clearly today.
Edit again
I've ran the query:
List<string> dates = MyTable.Select(t => t.Date.Date.ToString()).ToList();
and I'm getting results like 2011-08-05, so that portion obviously works.
However, when I run
DateTime.Today.Date.ToString()
I get 08/05/2011 00:00:00. Could the addition of this time portion be causing the issue? How would I remove this?
Edit 3
Got it to work using the code:
MyTable.Where(t => t.Date.Date.ToString() == DateTime.Today.Date.ToString("yyyy-dd-MM")).ToList();
This seems hacky though (converting to a string before comparison) and surely there must be a cleaner way?
It sounds like the date in the database isn't actually today (8th May). It's probably 5th August.
It looks like your datetime2 field is called Date. You need to use the Date property of this Date field to ignore the time of day.
MyTable.Where(t => t.Date.Date == DateTime.Today).ToList()

Linq to Entity get a Date from DateTime

var islemList = (from isl in entities.Islemler where (isl.KayitTarihi.Date >= dbas && isl.KayitTarihi.Value.Date <= dbit) select isl);
It gives error: date is not supported in LINQ to Entities...
How can i get date in linq.
Use EntityFunctions.TruncateTime.
if KayitTarihi is a date column in DB (and dbas and dbit are DateTime), use:
var islemList = (from isl in entities.Islemler where (isl.KayitTarihi >= dbas && isl.KayitTarihi <= dbit) select isl);
The .Date property is not supported in Linq to Entities (though it may be supported in other implementations of Linq).
I realize that you only want to compare the dates, but there is no real problem with comparing the datetimes if the dbas and dbit values are datetimes with time 00:00:00.
You might have to offset the dates or use other inequality checks to get the proper interval but the comparison will work as you intend.
I would personally go with Jandek's solution.

Categories