At approximately 12/1/2014 9:40:12 PM, the following code retrieves a null value.
Campaign camp = repo.Campaigns
.Where(ca => ca.StartTime <= DateTime.Now)
.Where(ca => ca.EndTime >= DateTime.Now)
.FirstOrDefault();
When there is a campaign in the database with the following values:
Start Time:
2014-11-30 00:00:00.000
End Time:
2014-12-02 00:00:00.000
I am at a complete loss why this would occur.
Try this:
Campaign camp = repo.Campaigns
.Where(ca => ca.StartTime.Value.Date <= DateTime.Now.Date && ca.EndTime.Value.Date >=DateTime.Now.Date).FirstOrDefault();
Have you taken timezone information into account? The stored data in the DB might have been created from a computer running in another timezone, your DateTime objects will have another timezone and when they are passed to the database they might exceed EndTime.
Your code works when working with in-memory data so the problem probably has something to do with timezones.
To comment on something else:
1. Don't chain multiple .Where clauses when you can do it with one.
2. Don't use DateTime.Now, store DateTime.Now in a value and then pass it into your LINQ, otherwise you'll compiare StartTime and EndTime against two different values.
var now = DateTime.Now;
Campaign camp = repo.Campaigns
.Where(ca => ca.StartTime <= now && ca.EndTime >= now)
.FirstOrDefault();
You're first opting for a DateTime less than current val. Let's say you got 2 results. Next for these 2 results, you're querying for the DateTime which is more than the current value! The results were less than current Date, so obviously they will never be more than the current Date val. I guess you're trying to do the following:
Campaign camp = repo.Campaigns
.Where(ca => ca.StartTime.Value.Date <= DateTime.Now.Date **||** ca.EndTime.Value.Date >=DateTime.Now.Date).FirstOrDefault();
It is happening because the time you are comparing like StartTime and EndTime are of different date format than the culture your DateTime.Now is picking up
**
DateTime.Now- 12/1/2014 9:40:12 PM
Start Time: 2014-11-30 00:00:00.000
End Time: 2014-12-02 00:00:00.000
**
Change your Datetime.Now date format into the same format as your StartTime and EndTime are
i.e 2014-12-01 9:40:12 PM
And then compare I am sure you will get the result
Related
I have a database table with columns of type dateTime.
Now I need to see if there already is a row with today's date, but I don't know how to compare the column with the current date without the hour, minutes, seconds.
Basically I have 2022-02-04 14:06:21.080 and I need to check if there is a row created on 2022-02-04.
I'm looking for something like
if (db.dates.Where(x => x.SentDate == Date.Now).Count() > 0)
{
// Do something
}
else
{
// Do something else
}
I only need to see if it has a date from today it doesn't matter what time it was created.
Any help is much appreciated!
If you're filtering for a specific date you can use the DateTime.Date property on both DateTime objects. This will compare the date component of the DateTime:
db.dates.Where(x => x.SentDate.Date == DateTime.Now.Date)
// or
db.dates.Where(x => x.SentDate.Date == DateTime.Today)
If you have a nullable DateTime? column, then you use the Value property along with HasValue:
db.dates.Where(x => x.SentDate.HasValue
&& x.SentDate.Value.Date == DateTime.Today)
Unfortunately, expression trees do not support the null propagation operator ?. so we need to use the above method instead.
DateTime.Date can also be used for date ranges, but take care with the upper bound.
PS: DateTime.Today is the same as DateTime.Now.Date
You can check a date range
var today = DateTime.Today;
var tomorrow = today.AddDays(1);
if(db.dates.Where(x => x.SentDate >= today && x.SentDate < tomorrow) ...
The DateTime.Today Property gets the current date with the time component set to 00:00:00.
You can check a date range
var today = DateTime.Today;
var tomorrow = today.AddDays(1);
if(db.dates.Where(x => x.SentDate >= today && x.SentDate < tomorrow) ...
The DateTime.Today Property gets the current date with the time component set to 00:00:00.
Note that we test the lower bound with >= today (with today meaning today at 00:00:00) but the upper one with < tomorrow, since we do not want to include tomorrow at 00:00:00.
Another way is to convert the dates to string and compare.
if(db.dates.Any(m=>m.SentDate.ToString("d") == DateTime.Now.ToString("d"))){
//Do something else
}
else
{
// Do something else
}
If you use MS SQL Server you can use a special function EF.Functions.DateDiff that was created to be used with EF. It can count datetime difference from seconds to months. DateDiffDay is used to count days.
var dateTimeNow = DateTime.Now;
if (db.dates.Any(x => EF.Functions.DateDiffDay(x.SentDate , dateTimeNow) == 0 )
{
// ... there are today's dates
}
// ...
Goal:
Searching between two selected date by datepickers.
Inserted dates format :
DateTime.Now()
result is: 2/23/2021 5:18:04 PM
Linq query :
var list = from d in ctx.SellInvoices
where d.Date >= dtpStartDate.SelectedDate.Value
&& d.Date <= dtpEndDate.SelectedDate.Value
select d;
Problem :
if dtpEndDate selected date is tommorow (2/24/2021) it returned result, but if i select today not returned any thing. what is problem here?
Addition:
if saved date as DateTime.Today() result is 2/23/2021 12:00:00 AM and search query returned good but for 12:00:01 AM should selecting one day later. Here I don't want to save with DateTime.Today().
If you have set dtpEndDate as just 2/23/2021 (today) it will actually be 2/23/2021 00:00:00
So when you compare d.Date <= dtpEndDate.SelectedDate.Value
It will be 2/23/2021 5:18:04 PM <= 2/23/2021 00:00:00.
I have bunch of records coming form the API response, but I just need to add some of the records in my database. I'm getting last record inserted in the database that is - fromDate = {7/5/2018 9:13:54 AM}. i need to get the records between that fromdate to latest record. But when tried, I'm getting 0 records due to datetime condition wrong.
sample data
RecordDateTime = {5/3/2018 7:29:00 PM}
fromDate= {7/5/2018 12:00:00 AM}
Code:
List<TransformerDetails> Pirs = Newtonsoft.Json.JsonConvert.DeserializeObject<List<TransformerDetails>>(responseString);
//Count = 10043
if (fromDate.HasValue)
{
Pirs = Pirs.Where(x => x.RecordDateTime > fromDate).ToList();
//fromDate= {7/5/2018 12:00:00 AM}
//count=0
}
Model
public DateTime RecordDateTime
{
get
{
string updtime = TimeZoneInfo.ConvertTimeFromUtc(Convert.ToDateTime(timestamp), TimeZoneInfo.FindSystemTimeZoneById("India Standard Time")).ToString();
return Convert.ToDateTime(updtime);
}
}
If you wanted to get the records between now and July 5th 2018, this is how you do it :
Pirs = Pirs.Where(x => x.RecordDateTime < fromDate && x.RecordDateTime > DateTime.Now).ToList();
Other than that, honestly... Your question seems to be concerning dates that haven't yet occurred, which is suspicious and I wonder if you really took enough time to think about what you are doing.
I am having trouble comparing times.
From what I have researched it most likely is due to the time not having a date.
My code,
This gets a dateTime value from the database.
var getDateTime = sql.Staff_Time_TBLs.Where(p => p.Staff_No ==
SelectedEmployee.Key && p.Date_Data == day).Select(p => p.Time_Data_1).ToList();
DateTime dateTimeGet = Convert.ToDateTime(getDateTime);
dateTimeGet returns a value like this "2012/12/12 15:03:00.000"
I then declare variables to hold the time.
TimeSpan startCompare = TimeSpan.Parse("15:00");
TimeSpan endCompare = TimeSpan.Parse("21:00");
Then comparing the values Compare DateTime
if ((endCompare > dateTimeGet) && (startCompare < dateTimeGet))
{
//match found
}
I am getting a compile error,
operands cannot be given to to type timespan and datetime
How do I compare times in this situation?
Just edit your code like this:
if ((endCompare > dateTimeGet.TimeOfDay) && (startCompare < dateTimeGet.TimeOfDay))
{
//match found
}
You could create DateTime values instead of TimeSpan to compare the value, using the Date of your db time:
DateTime startCompare = dateTimeGet.Date.AddHours(15);
DateTime endCompare = dateTimeGet.Date.AddHours(21);
if ((endCompare > dateTimeGet) && (startCompare < dateTimeGet))
{
// match found
}
In the example you showed, actually would be enough to compare the Hour part of dateTimeGet:
if (dateTimeGet.Hour >= 15 && dateTimeGet.Hour <= 21)
// match found
Actually you are comparing time with date in endCompare > dateTimeGet so you are getting the error
operands cannot be given to to type timespan and datetime
To compare time-span you need to extract the time from date in dateTimeGet by simply using TimeOfDay.
if ((endCompare > dateTimeGet.TimeOfDay) && (startCompare < dateTimeGet.TimeOfDay))
{
//match found
}
This will convert the date into time. For more details about TimeOfDayclick here Hope this works fine for you.
The issue is that, as you rightly say, you are comparing dates to times
A time-span is a measurement of time measured in Hours, where as a date-time is a measurement of time measured in days
so 2012/12/12 15:03:00.000 is approximately 735248.625 days or 17645967 hours
which you are then comparing to a timespan of 15 hours
so you need to either add 735248 days to your time span or drop 735248 days form your Date
both can be easily done
If you call the time TimeOfDay property on the date it will ignore the days and just return 0.625 days as 15 hours
Which means your code would look like this
if ((endCompare > dateTimeGet.TimeOfDay ) && (startCompare < dateTimeGet.TimeOfDay))
OR
If you add the time span to the at midnight date it will create the correct date time for comparation
Which means your code would look like this
if ((dateTimeGet.Date + endCompare > dateTimeGet ) && (dateTimeGet.Date + startCompare < dateTimeGet.TimeOfDay))
I'm trying to write a select query which returns records where the input date range falls between two date fields in a LINQ query.
My inputs are:
date1 - start date
date2 - end date
My database fields are
AppointmentStart
AppointmentEnd
Additionally, I'd also like to ensure that an input of 14:00 - 15:00 doesn't return a value for 15:00-16:00.
return (from t1 in db.Appointments where (t1.AppointmentStart <= date2 && (t1.AppointmentEnd) >= date1)
If anybody can assist me with this, I'd appreciate it.
I'm not 100% clear on your requirements. In your opening line you asked for records "where the input date range falls between two date fields", but in the "Additionally" line you imply that you don't want to return records where the start date of the appointment doesn't equal the end date of your input. I take these to be two different requirements, so I'll give you two different queries.
The first query is:
from t1 in db.Appointments
where date1 >= t1.AppointmentStart
where date2 <= t1.AppointmentEnd
select t1;
The second query is:
from t1 in db.Appointments
where date2 > t1.AppointmentStart
where date1 < t1.AppointmentEnd
select t1;
The first query returns records that "contain" the input dates.
The second query returns records that "overlap" the input dates.
I think it makes more sense that you want the overlap query and this one will meet your "14:00 - 15:00 doesn't return a value for 15:00-16:00" requirement.
Let me know if I made a mistake understanding your requirements and need to make any changes.
It looks backwards to me.
if the following is true:
Date1 = start
Date2 = end
then i would think startdate after or equal to appointmentstart and enddate before or equal to appointmentend or:
return (from t1 in db.Appointments where (date1 >= t1.AppointmentStart && date2 <= t1.AppointmentEnd))
i also changed the parens because they didn't make sense to me (seemed like one was missing)