I am trying to get data between two dates in a report viewer control in windows forms. Filtering report data, so I modified the dataset using parameters to
select SN,invoice_date,product_code........ where invoice_date >= #date1 and invoice_date <= #date2
I tried this also
select SN,invoice_date,product_code........ where invoice_date between #date1 and #date2
But the query is not returing any data, the datatype I used in SQL Server is date, and I changed the properties of the dataset #date1 and #date2 into date. So the problem is the datetimepicker am using is not working as it is adding time to the value. And I tried to validate the datetimepicker into something like
datetimepicker1.value.date.toshortdatestring() even tried datetimepicker1.value.tostring()
But the problem is, it will generate an error that system.datetime cannot be convert into string. I even change the datatype of the #date1 and #date2 into varchar in the dataset properties but still not loading.
So this is the code tried
this.Sales_InvoiceTableAdapter.FillByget(this.ProductREP.Sales_Invoice, ProductFrom.Value, ProductTo.Value, txtproductcode.Text);
this.Sales_InvoiceTableAdapter.FillByget(this.ProductREP.Sales_Invoice, ProductFrom.Value.Date, ProductTo.Value.Date, txtproductcode.Text);
What am I missing? I am using C# with SQL Server.
Assuming that the signature of Sales_InvoiceTableAdapter.FillByget is FillByget(string invoice, DateTime from, DateTime to, string productCode), then you should not need to convert to a string and you should check you're setting the time portion appropriately.
this.Sales_InvoiceTableAdapter.FillByget(this.ProductREP.Sales_Invoice, ProductFrom.Value.Date, ProductTo.Value.Date.AddDays(1), txtproductcode.Text);
Given a ProductFrom.Value and ProductTo.Value equal to 2020-04-28T10:55:00, the above code will result in ProductFrom.Value = 2020-04-28T00:00:00and ProductTo.Value = 2020-04-29T00:00:00.
If you want to only get values on that specific day (excluding midnight), then subtract 1 second from your final to value. e.g. ProductTo.Value.Date.AddDays(1).Subtract(TimeSpan.FromSeconds(1)).
Related
I am running a query in Vertica which returns a date as 2003-10-23 00:00:00
Now, In cs file, When I run filldataset to Dataset, the format get changes to '23-10-2003 00:00:00'
I want the exact format from database, As I tried to cast it as well but seems no result.
Date format returned from database gets changed according to our localculture display format while filling dataset, if we want it as it is then cast it as date and again cast as varchar in query, then fill the dataset in class.
In my Windows Form C# Application, I am inserting the record into the SQL server database. Along with other fields, I am also inserting both the current date and current time using the following format:
DateTime currentDate = DateTime.Now;
string SaleDate = currentDate.ToString("dd-MM-yyyy");
DateTime currentTime = DateTime.Now;
string SaleTime = currentTime.ToString("hh:mm:ss tt");
Which works fine and the records are inserted successfully with Date and Time format like .
However, when I select records between two dates, I am unable to perform this operation. I am sure that there is no problem in this custom format of my date because I have edited the same format several times and even I have saved the date in its default format but still I am unable to select the target records (between two dates)
I am using the following select query in my application to select records from the view vAllSales which results in selecting either all the records or records whose SaleDate does not meet the specified filter criteria:
select * from vAllSales where SaleDate >= '20-04-2019' and SaleDate <= '30-04-2019'"
I have tried the following queries in my SQL server as well to inspect the cause:
1.
select * from vAllSales where SaleDate between '21-04-2019' and '09-05-2019'
The above query does not return any value. Like
2.
select * from vAllSales where SaleDate >= '21-04-2019'
The above query select only a few records. Because 21-04-2019 is the initial SaleDate and the query should return all of the Sales but it only returns a few records, like .
Is there any issue with the specified date format within my code? Or do I have to work on improving my queries? I need a more professional and reliable approach for this case.
You should store your date and time as datetime2 objects in your database.
It will give you the benefits of:
better sorting: (your current string format does not allow a natural sort)
better performance; since your date and times are represented as numbers in stead of strings
easier to handle in code and queries: since it maps directly to a C# DateTime object.
For more info on database types see:
https://learn.microsoft.com/en-us/sql/t-sql/data-types/datetime2-transact-sql?view=sql-server-2017
And perhaps:
https://learn.microsoft.com/en-us/sql/t-sql/data-types/time-transact-sql?view=sql-server-2017
If you absolutely must use a string to represent your date, make sure it's in the sort-able ISO format.
YYYY-MM-DD
due to the nature of this format it's lexicographical sort-able as a string type.
You are trying to apply logical operations to string values. What will here happen is lexicographical comparing. (left to right).
So you better use correct data types to store data in table.
But If you really want to store date as a string, you have to cast them to proper data types before comparison.
select * from vAllSales where CAST(SaleDate AS DATE) >= '21-04-2019'
Keep note that ms sql server uses single quotes for pass datetimes. That doesn't mean those are strings or varchar
Why does C# still get the time from SQL if stored procedure only gets the date from a column:
CONVERT (DATE,RecordAdded, 103) as DateCaptured
Result:
I am selecting the date from a datetime column in SQL, then dumping it into a Listview. But I only want the date to display in the listview.
ListViewItem FeedbackTable = new ListViewItem(FeedbackReader["DateCaptured"].ToString());
Because a DateTime is a DateTime, containing both Date and Time part.
And DateTime.ToString() is implementented so it display also the Time part (which is 00:00, as result of your query)
Use the appropriate formatting for DateTime: e.g
myDateTime.ToString("d"); //short date pattern
or
myDateTime.ToString("dd/MM/yyyy"); // your custom display string
Now you have to create a ListViewItem with your correct date format; try this:
ListViewItem FeedbackTable = new ListViewItem(Convert.ToDateTime(FeedbackReader["DateCaptured"]).ToString("d"));
i.e., first you convert FeedbackReader["DateCaptured"]) (which is defined as object) to a DateTime, then apply the correct formatting (with ToString("d");) and then create your listviewItem with the desired string
I have found my solution. Logic actually, but so I learn...
I changed in SQL procedure this:
CONVERT (DATE,RecordAdded, 103) as DateCaptured,
To:
CONVERT (VARCHAR(10),RecordAdded, 103) as DateCaptured,
Now SQL converts it to a string after formatting it, giving me the result I want.
The Result I wanted
You can use the .ToString() for formatting your DateTime as string. Watch this link for more information. In your case this should work:
ListViewItem FeedbackTable = new ListViewItem(FeedbackReader["DateCaptured"].ToString("yyyy-MM-dd"));
Notice you maybe need to convert Convert.ToDateTime(FeedbackReader["DateCaptured"]);
UPDATE:
If you get the field as Date from your Database, it will be DateTime in C#. And DateTime always contains a Time Component. So what you can do is to modify the result from your StoredProcedure. How you can achieve this is described here.
Change the return Type of your StoredProcedure to string, so you can correctly show the information in your ListView:
SELECT LEFT(CONVERT(VARCHAR, #myDateTime, 120), 10);
I wanted to save only date in my database. There is a table which holds dates in database and the column which holds date in type of "Date". Now I want to store date from UI,so I placed WPF DatePicker in UI which allows to select date, but whenever I try to get the data from datepicker it shows the date and time.But I want just the dates to be stored in database.
This is the thing i am doing. It is demo code by the way. Can t upload original code. But this explains the thing. you can see in the message box, it shows 14-10-2015 00:00:00 , i want this zeros to be removed.
The dateTime Picker has a property DisplayDate of Type DateTime. This type contains date and time information.
Just use picker.DisplayDate.Date this returns a DateTime value with the TimeOfDay component set to 00:00.00
Edit
Usually you use an SQL Statement to insert or update values in the database. You should use a parametrized SQL statement with an parameter of type DateTime. The SQL API will take care of the conversion form DateTime (.Net type) to your SQL Date type and strip all time information away. It is a good idea to set the time component to 00:00:00 however to avoid any strange "roundings".
Use ToShortDateString() at the end something like:
var date = datePicker.SelectedDate.Value.Date.ToShortDateString();
MessageBox.Show(date.ToString());
this is my first question so pardon any mistakes that might occurs :)
I made a C# program that collects data from SQL Server Database using Datatables, and then export the results to Excel spreadsheets using Interop.
The program itself runs well and doing as it should; however, I found some bugs when it tries to select data with Date columns less than or equal to i.e. 2014-05-31 23:59:59.
Supposed I tried to get all data up to May 1st 2014.
My code first initiates the "Start Date" parameter for the SQL Command later used like this:
var firstDay = new DateTime(today.Year, today.Month, 1); //2014-05-01 00:00:00`
based on firstDay, it initiates the date for the parameter
var periodTo = firstDay.AddSeconds(-1);`
I debugged and got the time I wanted: 2014-04-30 23:59:59
After adding some more parameters for the data criteria, it executes the method to run the query using the parameters supplied.
queryResult = medicore.GenerateRegister(ConfigurationManager.AppSettings["queryDir"], ConfigurationManager.AppSettings["queryName"]);`
The periodTo parameter will be mapped to #EDate variable in the SQL Script. #EDate is declared as Datetime. The #Edate comes into play here:
Select columns
From tables
Where Voucher.Date <= #EDate
which I suppose, the script will be looks like Where Voucher.Date <= '2014-04-30 23:59:59'
The problem is, the result in the Excel file generated also consists of data from '2014-05-01', which is not supposed to be there...at least based on the criteria I set.
Is there some kind of rounding happened between C# and SQL Server?
Thanks!
The reason for this is probably that Voucher.Date is a SMALLDATETIME, therefore you are implicitly converting '2014-04-30 23:59:59' to a SMALLDATETIME:
SET DATEFORMAT MDY;
SELECT CONVERT(SMALLDATETIME, '2014-04-30 23:59:59')
Which gives '2014-05-01'.
Why not just use the Less than operator, instead of less than or equal to?
SET DATEFORMAT MDY;
SELECT ...
WHERE Voucher.Date < '2014-05-01';
N.B I have explcilty stated the DATEFORMAT because yyyy-MM-dd (despite being an ISO standard) is not culture invariant for the DATETIME and SMALLDATETIME data types in SQL Server, and if (like me) you are in a country where the default date format is DMY then SELECT CONVERT(SMALLDATETIME, '2014-04-30') will give you a conversion error. yyyyMMdd is the only culture invariant date format for these two types.
An excellent, and very relevant article to read is Aaron Bertrand's Bad habits to kick : mis-handling date / range queries