Exception on date format - c#

I have database with column of date type
My computer run on date format MM/dd/yyyy "en-us"
I have grid view which I used to insert data from GV to data base using the
insert SQL command it work fine with out any exception.
When I try to change my computer date format to dd/MM/yyyy
it give my exception when I run my application
("Does not allow to insert data from GV to data base column of date data type")
How can I solve this exception any help please?

Based on your description, it sounds as though you are using inline SQL to write the records to the database. If this is the case, then the correct approach is to format the DateTime in a standard way.
For SQL Server, the standard format is
theDate.ToString("yyyy-MM-dd HH:mm:ss.000")
However, it is strongly recommended to use parameterized SQL instead of inline SQL if possible (there are situations where it is not practical or possible). In this case, the parameters will handle the formatting of the date correctly so you don't have to worry about it.

Try to use DateTime.ParseExact
link to stackoverflow
In your case parsing from string to DB would be look like this
string s = "01/10/2014"; // format dd/MM/yyyy
DateTime dt =
DateTime.ParseExact(s, "dd/MM/yyyy", CultureInfo.InvariantCulture);

Related

asp.NET and SQL Server datetime issues

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.

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 convert the date that have been retrieve from DB to only display d/mm/yyyy?

I have this 21/10/1999 value manually inserted into the SQL database and when I retrieve it like this:
txtDOB.Text = readPatient["pDOB"].ToString();
It displays everything along with the time 12:00:00 AM. My data type for my date column is date, not datetime. So why is it displays the time as well?
((DateTime)readPatient["pDOB"]).ToString("d");
For a list of supported formats see: http://msdn.microsoft.com/es-es/library/zdtaw1bw(v=vs.110).aspx
You may try
txtDOB.Text = Convert.ToDateTime(readPatient["pDOB"]).ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
Edit: Thanks to comments saw that forgot to cast to datetime
It looks like you got your answer on how to properly format the value to a string without the time portion. But, no one has answered your other question:
So why is it displays the time as well?
This is because of mappings between SQL and .NET. In .NET a SQL "date" is stored in a DateTime object which does have time as well. To see all mappings between SQL and .NET see this: SQL Server Data Type Mappings
you can try this
txtDOB.Text=Convert.toDateTime(readPatient["pDOB"]).ToString("d/MM/yyyy");
You can use the string format parameter of the ToString to achieve any format you like,
like this:
TextBox1.Text =Convert.toDateTime(readPatient["pDOB"]).ToString("d/MM/yyyy");
Click on the datetimepicker then go to properties. There you can format your datetimepicker. Change format to custom (there few selection there) then set custom (provided in the properties menu) table with yy-MM-dd,an
DateTime dt = Convert.ToDateTime(sqdr["invdate"].ToString());
dt.Date; //To get the date only

SQL Server datetime issue?

C# code is reading data from database through dynamic queries.
Select ID, TransDate from Table_01
Business logic is processing the data and finally putting back the date into the database again.
INSERT INTO Table_02
( ID,ClosingDate) VALUES
( 1,Convert(DateTime, '27/07/2011 12:00:00 AM',120))
Since date format, i am inserting, is dd/MM/yyyy. Sql Server does not like it and .net throwing this error:-
The conversion of a char data type to a datetime data type resulted in
an out-of-range datetime value
If i change it to MM/dd/yyyy or yyyyMMdd then it works.
But system regional date time settings can be changed any time by any user, so I am looking for some concrete solution.
What is the best way to handle it?
The converstion style 120 is: yyyy-mm-dd hh:mi:ss(24h). Try using 103 (dd/mm/yyyy) instead.
INSERT INTO Table_02
( ID,ClosingDate) VALUES
( 1,Convert(DateTime, '27/07/2011 12:00:00 AM',103))
You can find the documentation for the styles here.
IMO the best way would be to use parameterized query - then the driver / server takes care of converting data into correct format.
Try setting the dateformat and using Cast:
Set DateFormat DMY
GO
INSERT INTO Table_02( ID,ClosingDate)
Select 1, Cast('27/07/2011 12:00:00 AM' As DateTime)
Stick to yyyyMMdd it will always work regardless of regional settings and date format settings. Beware of yyyy-MM-dd, it will not work when date format is DMY. http://www.sommarskog.se/wishlist.html#YYYYMMDD

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