for (DateTime date = fromDate; date <= toDate; date = date.AddDays(1))
{
var bwSalesValue = (from r in dtSalesData.AsEnumerable()
where r.Field<int>("PositionId") == pdPositionId
&& r.Field<DateTime>("SaleDate") == date
select r.Field<int>("SaleValue")).FirstOrDefault();
}
From the above snippet r.Field<DateTime>("SaleDate") == date part throws exception Specified cast is not valid.
date variable and dtSalesData rows have the same value 3/1/2015 12:00:00 AM
Any clue?
UPDATE==================================
Sorry friends, I did a silly mistake here. Problem is in the next line-
select r.Field<int>("SaleValue")).FirstOrDefault(); //Would be <decimal>
Please accept my apology. Thanks to all.
Have you tried doing this?
var bwSalesValue = (from r in dtSalesData.AsEnumerable()
where r.Field<int>("PositionId") == pdPositionId
&& Convert.ToDateTime(r.SaleDate) == date
select r.Field<int>("SaleValue")).FirstOrDefault();
for (DateTime date = fromDate; date <= toDate; date = date.AddDays(1))
{
var bwSalesValue = (from r in dtSalesData.AsEnumerable()
where r.Field<int>("PositionId") == pdPositionId
&& r.Field<DateTime>("SaleDate") == DBNull.Value ? DateTime.MinValue : date);
select r.Field<int>("SaleValue")).FirstOrDefault();
}
Maybe you shouldnt use where clause when SaleDate return DBNull.Value because it can't be convert DateTime to null.
Related
Check the CountEmailChart carefully. Here I am taking input of DateTime which is fully formatted date with time. But the problem is I want to compare only the date, not time, on Entity Framework below to count number of rows. Can anyone tell me how I can do this?
Controller code:
public int CountEmailChart(DateTime date, int campaignID)
{
int count = dbcontext.CampaignEmails
.Count(x => x.DateSigned == date && x.CampaignID == campaignID);
return count;
}
Karan's answer is correct but resulting query won't use an index for DateSigned. If a such index exist (or combined index for CampaignID and DateSigned columns) you may prefer this approach:
var startDate = date.Date;
var endDate = date.Date.AddDay(1);
int count = dbcontext.CampaignEmails.Count(x => x.CampaignID == campaignID && x.DateSigned >= startDate && x.DateSigned < endDate);
Try like this. .Date property on DateTime object will return only Date part.
If you are using Entity Framework 6 then.
date = date.Date;
int count = dbcontext.CampaignEmails.Count(x => DbFunctions.TruncateTime(x.DateSigned) == date.Date && x.CampaignID == campaignID);
Else
date = date.Date;
int count = dbcontext.CampaignEmails.Count(x => EntityFunctions.TruncateTime(x.DateSigned) == date.Date && x.CampaignID == campaignID);
Good day everyone. I'm new to C# but I can't seem to understand how DateTime work.
All I wanted to do is to check If a (givenday) = today and time is 7pm I wanted to return true. Is this the right way to do it?
Take note ActionDate is a field which is inputed by the user.
DateTime dateA = Convert.ToDateTime(ActionDate);
int a = dateA.Year;
int b = dateA.Month;
int c = dateA.Day;
int d = timeA.Hour;
int e = timeA.Minute;
var newDate = new DateTime(a, b, c, d, e, 0);
DateTime end = Convert.ToDateTime(newDate);
DateTime start = Convert.ToDateTime(A);
TimeSpan span = end.Subtract(start);
Decimal minutes = Convert.ToDecimal(span.TotalMinutes);
if
{
return true;
} else
{
return false;
}
Thank you in advance.
The way to check if a give date is today and is at 7pm is to use DateTime.Now.
Note that 19 is 7pm and 7 is 7am, the Hour property uses 24 hour format.
bool IsCurrentDayAnd7(DateTime dt) => dt.Date == DateTime.Now.Date && dt.Hour == 19;
As #TimSchmelter commented you could use DateTime.Today:
bool IsCurrentDayAnd7(DateTime dt) => dt.Date == DateTime.Today && dt.Hour == 19;
You can use Date property to compare date with current date.
if (newDate.Date == DateTime.Now.Date && newDate.Hour == 19)
{
return true;
}
You have made your code a bit too complicated. First, convert that user input to date, and compate it with current date and time.
DateTime dateA = Convert.ToDateTime(ActionDate);
if (dateA.Date == DateTime.Today && dateA.Hour == 19)
{
//it is current date and hour is 7pm
}
Alternatively, check if user's imput is ok, like this:
DateTime dateA;
if (!DateTime.TryParse(ActionDate, out dateA))
{
//alert user that he's entered wrong date
}
EDIT:
as Tim Schmelter noted, code's a bit more readable using DateTime.Today instead of DateTime.Now.Date
I am trying to compare date only. The value in table is DateTime with format
2014-01-29 09:00:00.000. Please advise thank you
public static List<vwReportDate> GetDetail(string startDate, string endDate)
{
startDate = "2014-01-28";
endDate = "2014-01-28";
DateTime dtStart = Convert.ToDateTime(startDate);
DateTime dtEndDate = Convert.ToDateTime(endDate);
var entities = new DataEntiies();
var query = from c in entities.vwReportDate
where c.EventCreateDate >= dtStart && c.EventCreateDate <= dtEndDate
select c;
return query.ToList();
}
It looks like you're using Entity Framework and LINQ to EF. If that's true you can't use DateTime.Date property because it's not supported in LINQ to EF. You have to use EntityFunctions.TruncateTime(myDateTime) static method instead:
var query = from c in entities.vwReportDate
let eventDate = EntityFunctions.TruncateTime(c.EventCreateDate)
where eventDate >= dtStart && eventDate <= dtEndDate
select c;
My approach to this problem, which does not depend on EF, is to use "less than" for the end of the date range (after moving the end of the date range one day forward):
startDate = "2014-01-28";
endDate = "2014-01-28";
DateTime dtStart = Convert.ToDateTime(startDate);
DateTime dtEndDate = Convert.ToDateTime(endDate).AddDays(1);
var entities = new DataEntiies();
var query = from c in entities.vwReportDate
where c.EventCreateDate >= dtStart && c.EventCreateDate < dtEndDate
select c;
return query.ToList();
Question: why do you ignore the argument values provided by the method's caller?
Use the Date property of a DateTime struct to retrieve the "date" part.
Gets the date component of this instance.
Use it in code:
var query = from c in entities.vwReportDate
where c.EventCreateDate.Date >= dtStart && c.EventCreateDate.Date <= dtEndDate
select c;
If you are using Entity framework (as it looks like you do), you'll have to use the EntityFunctions.TruncateTime (helper) method, because otherwise the query can't be converted.
var query = from c in entities.vwReportDate
where EntityFunctions.TruncateTime(c.EventCreateDate) >= dtStart && EntityFunctions.TruncateTime(c.EventCreateDate) <= dtEndDate
select c;
I want to get the today entered records using LINQ to SQL. I wrote the below code but it is returning previous date records also.
DateTime todaysDate = DateTime.Now;
DateTime yesterdaysDate = DateTime.Now.AddDays(-1);
var result = (from a in cxt.visitor.OrderByDescending(n => n.singin)
where (a.singin > yesterdaysDate && a.singin <= todaysDate)
select new {a.visitorid, a.visitorname, a.visitingperson, a.phonenumber, a.reasonforvisit, a.signature, a.singin });
Can you please tell me how to get the today entered records only using LINQ to SQL?
Insetad of DateTime.Now use DateTime.Today like:
DateTime startDateTime = DateTime.Today; //Today at 00:00:00
DateTime endDateTime = DateTime.Today.AddDays(1).AddTicks(-1); //Today at 23:59:59
var result = (from a in cxt.visitor.OrderByDescending(n => n.singin)
where (a.singin >= startDateTime && a.singin <= endDateTime)
select new {a.visitorid, a.visitorname, a.visitingperson, a.phonenumber, a.reasonforvisit, a.signature, a.singin });
or You can try the following simpler version, (I am not sure if that would translate into SQL)
var result = (from a in cxt.visitor.OrderByDescending(n => n.singin)
where (a.singin.Date == DateTime.Today)
select new {a.visitorid, a.visitorname, a.visitingperson, a.phonenumber, a.reasonforvisit, a.signature, a.singin });
I'm trying to get my linq statement to get me all records between two dates, and I'm not quite sure what I need to change to get it to work: (a.Start >= startDate && endDate)
var appointmentNoShow =
from a in appointments
from p in properties
from c in clients
where a.Id == p.OID && (a.Start.Date >= startDate.Date && endDate)
Just change it to
var appointmentNoShow = from a in appointments
from p in properties
from c in clients
where a.Id == p.OID &&
(a.Start.Date >= startDate.Date && a.Start.Date <= endDate)
var appointmentNoShow = from a in appointments
from p in properties
from c in clients
where a.Id == p.OID
where a.Start.Date >= startDate.Date
where a.Start.Date <= endDate.Date
var QueryNew = _context.Appointments.Include(x => x.Employee).Include(x => x.city).Where(x => x.CreatedOn >= FromDate).Where(x => x.CreatedOn <= ToDate).Where(x => x.IsActive == true).ToList();
So you are scrolling down because the Answers do not work:
This works like magic (but they say it has efficiency issues for big data, And you do not care just like me)
1- Data Type in Database is "datetime" and "nullable" in my case.
Example data format in DB is like:
2018-11-06 15:33:43.640
An in C# when converted to string is like:
2019-01-03 4:45:16 PM
So the format is :
yyyy/MM/dd hh:mm:ss tt
2- So you need to prepare your datetime variables in the proper format first:
Example 1
yourDate.ToString("yyyy/MM/dd hh:mm:ss tt")
Example 2 - Datetime range for the last 30 days
DateTime dateStart = DateTime.Now.AddDays(-30);
DateTime dateEnd = DateTime.Now.AddDays(1).AddTicks(-1);
3- Finally the linq query you lost your day trying to find (Requires EF 6)
using System.Data.Entity;
_dbContext.Shipments.Where(s => (DbFunctions.TruncateTime(s.Created_at.Value) >= dateStart && DbFunctions.TruncateTime(s.Created_at.Value) <= dateEnd)).Count();
To take time comparison into account as well :
(DbFunctions.CreateDateTime(s.Created_at.Value.Year, s.Created_at.Value.Month, s.Created_at.Value.Day, s.Created_at.Value.Hour, s.Created_at.Value.Minute, s.Created_at.Value.Second) >= dateStart && DbFunctions.CreateDateTime(s.Created_at.Value.Year, s.Created_at.Value.Month, s.Created_at.Value.Day, s.Created_at.Value.Hour, s.Created_at.Value.Minute, s.Created_at.Value.Second) <= dateEnd)
Note the following method mentioned on other stackoverflow questions and answers will not work correctly:
....
&&
(
s.Created_at.Value.Day >= dateStart.Day && s.Created_at.Value.Day <= dateEnd.Day &&
s.Created_at.Value.Month >= dateStart.Month && s.Created_at.Value.Month <= dateEnd.Month &&
s.Created_at.Value.Year >= dateStart.Year && s.Created_at.Value.Year <= dateEnd.Year
)).count();
if the start day was in this month for example and the end day is on the next month, the query will return false and no results, for example:
DatabaseCreatedAtItemThatWeWant = 2018/12/05
startDate = 2018/12/01
EndDate = 2019/01/04
the query will always search for days between 01 and 04 without taking the "month" into account, so "s.Created_at.Value.Day <= dateEnd.Day" will fail
And in case you have really big data you would execute Native SQL Query rather than linq
...
... where Shipments.Created_at BETWEEN CAST(#Created_at_from as datetime) AND CAST(#Created_at_to as datetime))
....
Thanks
If someone interested to know how to work with 2 list and between dates
var newList = firstList.Where(s => secondList.Any(secL => s.Start > secL.RangeFrom && s.End < secL.RangeTo))
public List<tbltask> gettaskssdata(int? c, int? userid, string a, string StartDate, string EndDate, int? ProjectID, int? statusid)
{
List<tbltask> tbtask = new List<tbltask>();
DateTime sdate = (StartDate != "") ? Convert.ToDateTime(StartDate).Date : new DateTime();
DateTime edate = (EndDate != "") ? Convert.ToDateTime(EndDate).Date : new DateTime();
tbtask = entity.tbltasks.Include(x => x.tblproject).Include(x => x.tbUser).
Where(x => x.tblproject.company_id == c
&& (ProjectID == 0 || ProjectID == x.tblproject.ProjectId)
&& (statusid == 0 || statusid == x.tblstatu.StatusId)
&& (a == "" || (x.TaskName.Contains(a) || x.tbUser.User_name.Contains(a)))
&& ((StartDate == "" && EndDate == "") || ((x.StartDate >= sdate && x.EndDate <= edate)))).ToList();
return tbtask;
}
this my query for search records based on searchdata and between start to end date
If you have date interval filter condition and you need to select all records which falls partly into this filter range. Assumption: records has ValidFrom and ValidTo property.
DateTime intervalDateFrom = new DateTime(1990, 01, 01);
DateTime intervalDateTo = new DateTime(2000, 01, 01);
var itemsFiltered = allItems.Where(x=>
(x.ValidFrom >= intervalDateFrom && x.ValidFrom <= intervalDateTo) ||
(x.ValidTo >= intervalDateFrom && x.ValidTo <= intervalDateTo) ||
(intervalDateFrom >= x.ValidFrom && intervalDateFrom <= x.ValidTo) ||
(intervalDateTo >= x.ValidFrom && intervalDateTo <= x.ValidTo)
);
I had a problem getting this to work.
I had two dates in a db line and I need to add them to a list for yesterday, today and tomorrow.
this is my solution:
var yesterday = DateTime.Today.AddDays(-1);
var today = DateTime.Today;
var tomorrow = DateTime.Today.AddDays(1);
var vm = new Model()
{
Yesterday = _context.Table.Where(x => x.From <= yesterday && x.To >= yesterday).ToList(),
Today = _context.Table.Where(x => x.From <= today & x.To >= today).ToList(),
Tomorrow = _context.Table.Where(x => x.From <= tomorrow & x.To >= tomorrow).ToList()
};
You can use DbFunctions.TruncateTime(StartDateTime) To remove the time from datetime
var appointmentNoShow =
from a in appointments
from p in properties
from c in clients
where a.Id == p.OID && (DbFunctions.TruncateTime(a.Start) >= DbFunctions.TruncateTime(startDate) && endDate)