asp.NET and SQL Server datetime issues - c#

I am having hard time to store date information into the datetime column of SQL Server.
I get the input from the user for three columns:
Creation Date
Preparation Date
Next Preparation Date
I use calendarextender and format the date as "yyyy/MM/dd". When all the fields have date, they are stored in the DB as for instance, 16-10-2016 (dd-MM-yyyy).
At this point I have two issues:
These columns are optional, when some of them are empty my code does not work (I assume because datetime cannot be null). To overcome this, I am using the following code snippet but still does not work.
DateTime? creationDate= null;
if (creationDateTextbox.Text != null && creationDateTextbox.Text != "")
{
creationDate= Convert.ToDateTime(creationDateTextbox.Text);
}
When I fetch the dates from DB, they are shown as 10/16/2016 (MM-dd-yyyy) which is different how I formatted it. I would like to show it in the format user enters them.

Dates do not have a format while stored in a database. It is actually usually just a very large long that counts the number of milliseconds from a set starting date.
If you want to store the format you need to stop storing it as dates and instead just treat the text as text in the database, however if you do this you won't get the advantage of sorting or filtering by a date range because it will just be seen as text.

Date time doesn't have any format You can format is as a string, suppose your DateTime type database field dt which contain date as 10/16/2016 (MM-dd-yyyy) then you can convert it
string s = dt.ToString("yyyy/MM/dd");

The answer to one of your questions is here: MSDN
You can use data annotations to format the dates that you get from your SQL DB. I'm assuming that you're using EF6; if not, you can change the field to a varchar in SSMS, and store the date as a String.
And the second, I'm unclear about, but if what you want is for your SQL DB column to be optional, you can use the Optional data annotation for that.

Related

Unable to select records between date range

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

Datetime format is 'mm-dd-yyyy' when getting while using SqlDataAdapter but if I run the same query in ms sql then its 'yyyy-mm-dd'

I know the question is a bit confusing. Please let me elaborate.
Suppose
I have a table student master which has a column DOB
I have inserted a record and in DOB I have inserted '1991-01-01'
running select statement from sql server is returning date in the same format as it is inserted '1991-01-01' but when I am running the same query from C# using SqlDataAdapter then its returning date as '01-01-1991'
Can anyone explain why it is happening and is there any way to fetch the date in same format as it is inserted.
Query
Is it possible to get the DateTime using SqlDataAdapter as it was inserted?
P.S: column data type is Datetime
let's separate the wheat from the chaff :)
if for your needs meaningful is data type (datetime in this case), then formatting does not matter at all. All layers which will exchange or process the data will use data type information for that.
But
if the meaningful part is formatting, i.e. string representation of the data, then you need to consider the appropriate settings of UI tools you use to display your data. SSMS, for example, uses regional settings for that. If you need to visualize data in the identical manner, so you need the identical strings, you should take care of formatting by your self or in another words, you need to convert your datetime data to string in the same way in all places where you need it.
In T-SQL, for example, you could use CAST and CONVERT functions for formatting your data in a format you need.
If you can't match up the "Cultures" between the SQL Server and the machine you're building the application on (and, in fact, you cannot rely on that really if you're application is going to be deployed to other machines!), then the cheap and quick way round it is to run your date returns through a parse function such as this:
private string FncFormatDate(string date)
{
DateTime formattedDate;
if (DateTime.TryParse(date, out formattedDate))
{
return formattedDate.ToString("yyyy-MM-dd");
}
else
{
return "Invalid date";
}
}
I hope this answers your question.

How to save date only from WPF datepicker using c#?

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());

To Get Data that its type is Date in C#

In my SQL database, I have BeginDate column of type date (so I want to get only day,month,year).
I add data into database in C#.
I look at Table_Data and everything is fine (for example BeginDate = 05/04/2014).
But when I get this data from database in C# with
string a= dt.Rows[i]["BeginDate"].ToString()
result is: a= 05/04/2014 12:00:00 AM
Why?
I can remove hour in string a with any methods. But why? I want to get only 05/04/2014 from database.
This is a display problem, not a data problem. Use the Formatting features of DateTime.ToString() to display the date in the format that you want.
If the data is coming out of the database in string form, use DateTime.Parse on it first.
Reference
Standard Date and Time Formats
Custom Date and Time Formats

How to change date format in mysql stored procedure insert statement "22-12-2010" to "2010-12-22"

I send the registration date parameter to mysql database like "22-12-2010". But my sql date date type is in another format how can I change the date format like "2010-12-22" also I have to insert this into table.
Give code in C#,asp.net code behind either sql query statement!
Use this comprehensive MSDN pages as your guide: Standard Date and Time Format Strings and Custom Date and Time Format Strings.
There are many examples on those pages on how to reformat a date string in C#, and they also provide a good clear explanation on how date formatting works in the DateTime class.
Once you've reformatted your date string in C#, you should be able to pass it on down without needing to use SQL to reformat it.

Categories

Resources