سؤال

I have an SQL query which should return some data between two dates that are selected using two datetime pickers, but when both the dates are equal it should return the data for that day instead. My query doesn't return anything as my date is in mm/dd/yyyy hh:mm:ss AM/PM format. I use the following date format from my datetime picker

dtpEndDate.Value.ToShortDateString()

For example when my end date is 4/13/2014 then it returns the data which is before 4/13/2014 00:00:00 but I would like the data until 4/13/2014 23:59:59

I have the following query

SELECT   
  sum(isnull(ExpectedAmt, 0)) AS Payment  FROM  Sales                            
  WHERE  (a.SellDate >= @StartDate)  AND (a.SellDate <= @EndDate) 

I tried casting the data time but was not able to convert it to date time type. Is there any better way I could do this?

هل كانت مفيدة؟

المحلول

Check if the Date part of the datetime is the same. If so, adjust the values accordingly

if(firstDate.Date.Equals(secondDate.Date))
{
    firstDate = firstDate.Date; 
         //If any time of day was set, it's now 0:00:00

    secondDate = firstDate.AddDays(1).AddSeconds(-1); 
         //This is now the day with time 23:59:59
}

At that point, you can continue your regular filtering.

نصائح أخرى

If your SQL database is MS SQL Server, you can use the DATEDIFF function. Your SQL fails because both your DateTime objects have 0 hours/minutes/seconds and the data in your table presumably don't.

DATEDIFF(DAY, date1, date2) <= 0 is true if date1 is later than or the same as date2, ignoring any unit of time smaller than a day.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top