Compare datetime column just year (without time-day-month) with Linq - linq

I want to get a 2022 records. But my code is not efficient. How to compare it?
> var _year = "2022"; list= query.Where(x =>
> Convert.ToDateTime(x.created_time).ToString("YYYY").Equals(_year
> )).ToList();

Is better not to change type to string, but get DateTime structure Year property.
Code example:
var year = 2022;
var list = query.Where(x => Convert.ToDateTime(x.created_time).Year.Equals(year)).ToList();

Related

Performing a date comparison with a date field stored in the database

I am trying to compare todays date with a date in the database.
Todays date is saved in the database like this : 2016-06-14 00:00:00.000
dtTodaysDate is generated like this: 6/14/2016 11:51:09 AM
Here is the method
public string CheckCreateOneProjectReportPerDay(string strprojectId)
{
string checkReturnValue = "DoesNotExist";
DateTime dtTodaysDate = DateTime.Now;
var checkProjectRec =
_objContext.tbl_Project_Status_MSTR.Where(
s => s.ProjectID == strprojectId && s.StatusDate == dtTodaysDate);
if (checkPrjDate.Any())
{
checkReturnValue = "RecordExist";
}
return checkReturnValue;
}
I tried to use the keyword contains in the query below but no luck
var checkProjectRec =
_objContext.tbl_Project_Status_MSTR.Where(
s => s.ProjectID == strprojectId && s.StatusDate == dtTodaysDate);
The query above will always return nothing because they don't match. Is there a better way
of doing this comparison ?
It looks like your database column StatusDate only stores the Day, Month, and Year of its DateTime object.
I would recommend altering your linq query to search for only those values of dtTodaysDate.
Give this a try:
var checkProjectRec =
_objContext.tbl_Project_Status_MSTR.Where(
s => s.ProjectID == strprojectId
&& s.StatusDate.Year == dtTodaysDate.Year
&& s.StatusDate.Month == dtTodaysDate.Month
&& s.StatusDate.Day == dtTodaysDate.Day);
Linq-to-SQL: DateTime Methods might be worth looking into as well.

Limiting a query to the rows created today (Linq-to-Entities, Datetime)

So I've got this query:
var query = from r in context.Cars
let h = context.CarHistories
.Where(u => r.ID == u.CarID)
.Where(u => u.EventID == intEventID)
.OrderByDescending(u => u.CreatedDate)
.FirstOrDefault()
select new RefundListItem()
{
ID = r.ID,
VendorID = r.VendorID,
RecipientName = r.RecipientName,
MostRecentSubmittedName = h.CreatedName,
CreatedDate = h.CreatedDate,
};
Later on, I add this to the query because I only want the rows that were created today:
DateTime today = DateTime.Today;
query.Where(u => Convert.ToDateTime(u.CreatedDate) >= today);
For some reason, this where statement does not affect the query at all. The query still returns items created from previous days instead of limiting them to just the rows created today.
I have also tried this but it does not work either:
DateTime today = DateTime.Today.Date;
query.Where(u => Convert.ToDateTime(u.CreatedDate.Date) >= today.Date);
I'm using Linq-to-Entities (MVC 4, EF 4).
Where does not modify query instance, it returns new one with additional condition added. Assign it back to query to make it work:
query = query.Where(u => Convert.ToDateTime(u.CreatedDate.Date) >= today.Date);

How can I get the last date from a list of dates in the database then compare it with the current date?

I’m trying to retrieve dates from the database then use it to compare with current date. How can I get the last date from a list of dates in the database then compare it with the current date? Here’s what I’ve tried but I get a exception: “LINQ to Entities does not recognize the method 'System.DateTime Last…”
var manageDate= from d in db.Enrollments.Select(da=>da.Date) select d;
var manageAssgnDate = from asgn in db.Enrollments.Select(asgn => asgn.Date) select asgn;
List<DateTime> newDate = manageDate.ToList();
I normally use lambdas:
// This gets the max date in the table
var manageDate = db.Enrollments.Max(da => da.Date);
Is this what you were asking for ?
Found a work-around:
var stdAssgn= from sa in db.Assignments where sa.StudentId==currentId select sa.Date;
var dt = stdAssgn.ToList().Last ();
String a = dt.ToString();
and to convert to DateTime if needed...
DateTime b=Convert.ToDateTime(a);

Filtering by Date (linq)

I have DateTime field named "repeat" in database. I want to take only records which Date in "repeat" is today.
I tried :
(...).Where(e => e.repeat.Value.Date.Day.Equals(DateTime.Now.Day));
or:
(...).Where(e => e.repeat.Value.Date.Day==DateTime.Now.Day);
but it doesn't work.
Any ideas?
Thanks,Kamil
"It doesn't work" is pretty vague, but currently you're checking the day of the week rather than the date. I would suggest using:
Date today = DateTime.Today;
var query = ....Where(e => e.repeat.Value.Date == today);
EDIT: It's not clear what the types involved here are - if repeat.Value is not itself a DateTime, you may want:
var query = ....Where(e => e.repeat.Value.Date.Date == today);
Give this a try:
(...).Where(e => (e.repeat >= DateTime.Today) && (e.repeat < DateTime.Today.AddDays(1)))
Compare short date ensures you the year/month/day are the same in one shot :
(...).Where(e => e.repeat.Value.Date.ToShortDateString() == DateTime.Now.ToShortDateString());
Expert Solution is: Use DbFunctions.CreateDateTime() in Linq Query.
var date = DateTime.Now.AddDays(-1).Date;
var actions = await _context.Set<Your_table>()
.AsNoTracking()
.Where(x => DbFunctions.CreateDateTime(x.YourColumn.Value.Year, x.YourColumn.Value.Month, x.YourColumn.Value.Day, 0, 0, 0) == date)
.ToListAsync();

LINQ - how to get next three business days excluding dates in table?

I need to find the next three available business days for a scheduling application. What is available depends upon excluded dates in a table. So...as long as the date is not in my table and not a Saturday or Sunday, I want the next three. I'd like to find an efficient way of doing this.
I need to return a List<DateTime>. The table is simple - ExcludedDates has an ID and a DateTime with the excluded date.
I'd like to have a single LINQ query expression but can't figure it out...thanks to all in advance and I apologize if this is trivial or obvious - it isn't to me.
Try this...
DateTime start = DateTime.Now.Date;
var result = Enumerable.Range(1, 10) // make this '10' higher if necessary (I assume you only exclude non-workingdays like Christmas and Easter)
.Select(offset => start.AddDays(offset))
.Where(date => !( date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek== DayOfWeek.Sunday))
.Where(d=> !exceptionTable.Any(date => date == d))
.Take(3).ToList();
List<DateTime> result = (from i in Enumerable.Range(1, excludeTable.Rows.Count + 6)
let date = inputDate.AddDays(i)
where date.DayOfWeek != DayOfWeek.Saturday &&
date.DayOfWeek != DayOfWeek.Sunday &&
!excludeTable.Rows.Cast<DataRow>().Select(r => (DateTime) r["ExcludeDate"]).Contains(date)
select date).Take(3).ToList();
excludeTable.Rows.Count + 6 is to cover the worst case where you skip over every thing in the excludeTable and then you have to skip over another weekend.
This assumes that a month will be reasonable depending on your excluded dates.
DateTime date = DateTime.Today;
// first generate all dates in the month of 'date'
var dates = Enumerable.Range(1, DateTime.DaysInMonth(date.Year, date.Month)).Select(n => new DateTime(date.Year, date.Month, n));
// then filter the only the start of weeks
var results = (from d in dates
where d.DayOfWeek != DayOfWeek.Saturday && d.DayOfWeek != DayOfWeek.Saturday && !excludes.Any(i => i.DateTime.Date == d.Date) && date < d
select d).Take(3);
var excludedList = new List<long>() { DateTime.Parse("2011-07-27").Ticks };
var week = new List<long>(){
DateTime.Now.Date.Ticks,
DateTime.Now.Date.AddDays(1).Ticks,
DateTime.Now.Date.AddDays(2).Ticks,
DateTime.Now.Date.AddDays(3).Ticks,
DateTime.Now.Date.AddDays(4).Ticks,
DateTime.Now.Date.AddDays(5).Ticks,
DateTime.Now.Date.AddDays(6).Ticks,
DateTime.Now.Date.AddDays(7).Ticks,
DateTime.Now.Date.AddDays(8).Ticks
};
var available = (from d in week.Except(excludedList)
where new DateTime(d).DayOfWeek != DayOfWeek.Saturday && new DateTime(d).DayOfWeek != DayOfWeek.Sunday
select new DateTime(d)).Take(3);
foreach (var a in available)
Console.WriteLine(a.ToString());

Resources