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
Related
I have a weird problem with sql server 2008. I am trying to save date with dd/MM/yyyy format into sql server 2008, But after inserting date it automatically get converted into MM/dd/yyyy.
Note : my computer clock format is dd/MM/yyyy
My report viewer date text box properties
enter image description here
Date from my database table
enter image description here
my c# code
lbldate.Text = DateTime.Today.ToShortDateString();
date on report
05/04/2017
SQL Server is the Data Layer and as such there is no formatting available; it stores a date as a 4 byte number which is relative to days with 0 = 01/01/1900.
The Application Layer DateTime type is generally an ODBC Canonical representation which basically looks like a class with integer properties for each component (year, month, date, hours, minutes, seconds, milliseconds).
The Presentation Layer is what you actually see, and that is where you should be concerned. When your application calls the ToShortDateString() method, it is calling the display format from the threads current culture, which may or may not reflect the systems settings for Region & Language or Date & Time.
Solution number one is to set the threads current culture, but this would just go to that particular cultures standard display
Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");
Solution number 2 is to just use a custom DateTime format string
lbldate.Text = DateTime.Today.ToString("dd/MM/yyyy");
I would not say this is a "problem" so to speak. This is how SQL handles dates. Your computer clock format is not relevant. To change the format, use CONVERT in your queries. Ex:
SELECT CONVERT(varchar, GETDATE(), 103)
Results: 04/05/2017
SELECT CONVERT(varchar, GETDATE(), 101)
Results: 05/04/2017
The codepage arguments are listed here: https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql
edit per your new update: Your C# should look something like this:
DateTime.Now.ToString("dd/mm/yyyy")
What you're seeing is how the query tool presents results and has nothing to do with how Sql Server stored the data. Sql Server actually stores dates in a binary (not readable) format.
This is a good thing. Let Sql Server store dates (and other data) how it wants. You only need to worry about how you show the data to users after you retrieve it, and most of the time the best place to worry about that formatting isn't even in the server at all, but in your client language.
I have a SQL Server 2012 Express database that has been installed on a server in Germany. I created a database and have now realised the date formats are incorrect. I need to show each date as dd/mm/yyyy.
When I run dbcc useroptions (after making some changes to the server), I get the following -
language dateformat
-------------------------
British dmy
When I run select GetDate() in a new query, it shows the date as follows -
2014-08-28 13:53:10.550
The bottom line issue is when I enter 28/08/2014 in to a textbox on a web forms project, it errors
String was not recognized as a valid DateTime.
selP.StartDate = Convert.ToDateTime(tbStartDate.Text);
Any ideas why this is happening? I have created a new user since changing the settings to British and dmy, which still produces the same error.
SQL Server doesn't store a DateTime in any string format - it's stored as an 8 byte numerical value.
The various settings (language, date format) only influence how the DateTime is shown to you in SQL Server Management Studio - or how it is parsed when you attempt to convert a string to a DateTime.
There are many formats supported by SQL Server - see the MSDN Books Online on CAST and CONVERT. Most of those formats are dependent on what settings you have - therefore, these settings might work some times - and sometimes not.
The way to solve this is to use the (slightly adapted) ISO-8601 date format that is supported by SQL Server - this format works always - regardless of your SQL Server language and dateformat settings.
The ISO-8601 format is supported by SQL Server comes in two flavors:
YYYYMMDD for just dates (no time portion); note here: no dashes!, that's very important! YYYY-MM-DD is NOT independent of the dateformat settings in your SQL Server and will NOT work in all situations!
or:
YYYY-MM-DDTHH:MM:SS for dates and times - note here: this format has dashes (but they can be omitted), and a fixed T as delimiter between the date and time portion of your DATETIME.
This is valid for SQL Server 2000 and newer.
If you use SQL Server 2008 or newer and the DATE datatype (only DATE - not DATETIME!), then you can indeed also use the YYYY-MM-DD format and that will work, too, with any settings in your SQL Server.
Don't ask me why this whole topic is so tricky and somewhat confusing - that's just the way it is. But with the YYYYMMDD format, you should be fine for any version of SQL Server and for any language and dateformat setting in your SQL Server.
The recommendation for SQL Server 2008 and newer is to use DATE if you only need the date portion, and DATETIME2(n) when you need both date and time. You should try to start phasing out the DATETIME datatype if ever possible
The proper way to achieve that is to set the culture of your web application.
How to: Set the Culture and UI Culture for ASP.NET Web Page Globalization
IN SQL, you need to cast that string as a DATETIME before inserting or updating the database.
CAST('28/08/2014' AS DATETIME)
You can change the format a date is displayed in using the CONVERT. For example, the following will display the date in UK short format (dd/mm/yyyy)
SELECT CONVERT(varchar(50), GetDate(), 103)
If you are doing this in C#, you need to detect the local culture and cast the string to a datetime as approporate.
//You can set the culture on the current thread:
Thread.CurrentThread.CurrentCulture = CultureInfo.InstalledUICulture; // or new CultureInfo("en-GB"); //dd/MM/yyyy
//or you can pass it to the DateTime.Parse method. Something like this:
DateTime startDate = DateTime.Parse(tbStartDate.Text, CultureInfo.InstalledUICulture);
DateTime startDate = DateTime.ParseExact(tbStartDate.Text,"dd/MM/yyyy",System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat)
Actually the GETDATE() function returns the system date and time in the format 'yyyy-mm-dd hh:mi:ss.mmm' irrespective of the Dateformat.Date format for SQL server is in U.S. date format MM/DD/YY, unless a localized version of SQL Server is installed which seems to be the case here.
Use
SET DATEFORMAT <format>
which sets the order of the date parts (month/day/year) for entering datetime or smalldatetime data. Valid parameters include mdy, dmy, ymd, ydm, myd, and dym. The U.S. English default is mdy.
This method allows you use a date format for dates sent to SQL Server of d/m/y, but it is connection dependent. If a new connection is made to SQL Server or if the server is stopped and restarted, the date format will go back to dmy which is default in your case.
selP.StartDate=tbStartDate.Text.ToString("dd/MM/yyyy")
SELECT CONVERT(varchar(50), GetDate(), 103)
SELECT CONVERT(varchar(50), JoiningDate, 103)from Employee where EmpId='1001'
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);
hi i want to cast Datetime Column. Actually my system Datetime format is MM/dd/yyyy
but client systems contains different different Datetime formats. then how can i search based on Datetime column in SQL.Know i am doing Converting
(Datetime BETWEEN CONVERT(DATETIME, '1980-10-10 00:00:00', 102) AND CONVERT(DATETIME, '1990-10-10 00:00:00', 102))
but it works when the Client System has Same Format. If the Client System has different DateTime Format.It gives an Error.
YYYYMMDD will always work, and your client language should be able to use date/time without ever worrying about format anyway. Use a properly parameterized query and you won't have to worry about the format of the string. Also, you shouldn't ever use BETWEEN for date ranges, and I don't know why you think you need a CONVERT here. The underlying column is DATETIME right?
WHERE column >= '19801010' AND column < '19901011';
What do BETWEEN and the devil have in common?
Bad habits to kick : mis-handling date / range queries
SQL:
select *
from tvideoconference
where del = 'false'
and iduserpatient = 0 and startdate >= N'18.02.2013 20:37:07'
order by startdate
Error:
The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.
I got this error, when I tried to use method below in de-DE session culture. What is more, in pl-PL and en-US culture, this methods works perfect.
public static DataSet getSpecialistConfs(int iduserspecialist)
{
DateTime? today = DateTime.Now;
today = today.Value.AddHours(-today.Value.Hour).AddMinutes(-(today.Value.Minute + 1));
string sql = "select * from tvideoconference where del='false' and startdate >=N'" + today.Value + "' and iduserspecialist=" + iduserspecialist;
sql += " order by startdate ";
return Tools.SQLTools.getDataSet(sql);
}
How can I resolve it? I tried with many solutions (substrings, date format), with the same effect..
How can I resolve it?
Use parameterized SQL in the first place. Don't include the values in your query itself; use parameters and set the values of those parameters.
It's unclear what Tools.SqlTools is, but you really, really should use parameterized SQL. That way you won't be converting the DateTime value into a string to start with, so cultures and formatting can't get in the way. Additionally, you won't be vulnerable to SQL injection attacks...
(Additionally, it's not at all clear why you're using DateTime? instead of DateTime - it's not like DateTime.Now can be null... and you should consider using DateTime.Today instead... or DateTime.UtcNow.Date.)
The various settings (language, date format) only influence how the DateTime is shown to you in SQL Server Management Studio - or how it is parsed when you attempt to convert a string to a DateTime.
There are many formats supported by SQL Server - see the MSDN Books Online on CAST and CONVERT. Most of those formats are dependent on what settings you have - therefore, these settings might work some times - and sometimes not.
The way to solve this is to use the (slightly adapted) ISO-8601 date format that is supported by SQL Server - this format works always - regardless of your SQL Server language and date format settings.
The ISO-8601 format is supported by SQL Server comes in two flavors:
YYYYMMDD for just dates (no time portion); note here: no dashes!, that's very important! YYYY-MM-DD is NOT independent of the dateformat settings in your SQL Server and will NOT work in all situations!
or:
YYYY-MM-DDTHH:MM:SS for dates and times - note here: this format has dashes (but they can be omitted), and a fixed T as delimiter between the date and time portion of your DATETIME.
This is valid for SQL Server 2000 and newer.
If you use SQL Server 2008 or newer and the DATE datatype (only DATE - not DATETIME!), then you can indeed also use the YYYY-MM-DD format and that will work, too, with any settings in your SQL Server.
Don't ask me why this whole topic is so tricky and somewhat confusing - that's just the way it is. But with the YYYYMMDD format, you should be fine for any version of SQL Server and for any language and dateformat setting in your SQL Server.