How do I modify the datetime format in Microsoft SQL Server? - datetime

I'm testing a query that I think is handling datetime values in a way that may not work for customers who aren't using a specific datetime format.
Here's the code:
WHERE order_instant >= CONCAT(YEAR(cast(getdate() as date)) ,'-01-01')
I suspect this code would break if a customer had datetimes formatted as anything other than year - month - day, but I'm having trouble testing that hunch.
The column datatype is datetime.
I'm looking for something analogous to the NLS settings in Oracle SQL Developer, which allows me to do things like display dates as YYYY-MON-DD or MM-DD-YY.
Any ideas? Thanks!

Related

Issue with date when migrating databases between SQL Server 2008 and 2012 [duplicate]

I have the following piece of inline SQL that I run from a C# windows service:
UPDATE table_name SET
status_cd = '2',
sdate = CAST('03/28/2011 18:03:40' AS DATETIME),
bat_id = '33acff9b-e2b4-410e-baaf-417656e3c255',
cnt = 1,
attempt_date = CAST('03/28/2011 18:03:40' AS DATETIME)
WHERE id = '1855'
When I run this against a SQL Server database from within the application, I get the following error:
System.Data.SqlClient.SqlException: The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.
But if I take the piece of SQL and run it from SQL Management Studio, it will run without issue.
Any ideas what may be causing this issue?
Ambiguous date formats are interpreted according to the language of the login. This works
set dateformat mdy
select CAST('03/28/2011 18:03:40' AS DATETIME)
This doesn't
set dateformat dmy
select CAST('03/28/2011 18:03:40' AS DATETIME)
If you use parameterised queries with the correct datatype you avoid these issues. You can also use the unambiguous "unseparated" format yyyyMMdd hh:mm:ss
But if i take the piece of sql and run it from sql management studio, it will run without issue.
If you are at liberty to, change the service account to your own login, which would inherit your language/regional perferences.
The real crux of the issue is:
I use the following to convert -> date.Value.ToString("MM/dd/yyyy HH:mm:ss")
Please start using parameterized queries so that you won't encounter these issues in the future. It is also more robust, predictable and best practice.
I think the best way to work with dates between C# and SQL is, of course, use parametrized queries, and always work with DateTime objects on C# and the ToString() formating options it provides.
You better execute set datetime <format> (here you have the set dateformat explanation on MSDN) before working with dates on SQL Server so you don't get in trouble, like for example set datetime ymd. You only need to do it once per connection because it mantains the format while open, so a good practice would be to do it just after openning the connection to the database.
Then, you can always work with 'yyyy-MM-dd HH:mm:ss:ffff' formats.
To pass the DateTime object to your parametrized query you can use DateTime.ToString('yyyy-MM-dd HH:mm:ss:ffff').
For parsing weird formatted dates on C# you can use DateTime.ParseExact() method, where you have the option to specify exactly what the input format is: DateTime.ParseExact(<some date string>, 'dd/MM-yyyy',CultureInfo.InvariantCulture). Here you have the DateTime.ParseExact() explanation on MSDN)
It's a date format issue. In Ireland the standard date format for the 28th of March would be "28-03-2011", whereas "03/28/2011" is the standard for the USA (among many others).
I know that this solution is a little different from the OP's case, but as you may have been redirected here from searching on google the title of this question, as I did, maybe you're facing the same problem I had.
Sometimes you get this error because your date time is not valid, i.e. your date (in string format) points to a day which exceeds the number of days of that month!
e.g.: CONVERT(Datetime, '2015-06-31') caused me this error, while I was converting a statement from MySql (which didn't argue! and makes the error really harder to catch) to SQL Server.
You could use next function to initialize your DateTime variable:
DATETIMEFROMPARTS ( year, month, day, hour, minute, seconds, milliseconds )
JAVA8: Use LocalDateTime.now().toString()
i faced this issue where i was using SQL it is different from MYSQL
the solution was puting in this format:
=date('m-d-y h:m:s');
rather than
=date('y-m-d h:m:s');

Different date types manipulation

I am currently stuck with a database issue where I need to manipulate data using my database inserts. I am currently doing a website with C# ASP.NET on Visual studio 2012 and the database I am using is SQL Management 2008.
Firstly, I currently store my System.Date into a string and store it as a nvarchar datatype in my database. If I would like to perhaps get the latest 10 rows from for example, user= 'x', how should I actually go about doing the SELECT statement to only get the data I specified?
And I currently store information like Date Of Birth using the calander Ajax toolkit so the format the dates are saved in is in month/day/year format. The data is stored into my database as a nvarchar as well. If I want to perhaps calculate the age of user='x' how should I calculate it?
I think Jon's comment about storing the data properly as a datetime is spot on:
Why are you storing it as an nvarchar to start with? It's logically a
date/time, not a string - so store it as a date/time. Get rid of the
string part, and all your formatting problems go away too.
Definitely do that if you can.
If, for some reason, you can't change your database structure, you can use a CAST / CONVERT statement in your ORDER BY clause to get what you want:
SELECT TOP 10 *, CAST(yourDateField AS datetime) AS convertedDate
FROM yourTable
WHERE
user='Some user'
ORDER BY CAST(yourDateField AS datetime) DESC
This assumes that your nvarchar data can be properly converted to a datetime (which it should be if you're using the Ajax Control Toolkit calendar extender).

SQL Express storing date in MM/DD/YYYY format

I have an ASP.NET program that is writing date to an SQLExpress Database date field in DD/MM/YYYY.
When I look at the data in SQL Express it is stored as mm/dd/yyyy.
How can I configure it to store in DD/MM/YYYY format?
This is not possible, as the date is internally stored as a number, the DD/MM/YYYY or MM/DD/YYYY format is only the display format of the data. You can, however, change the way the data are converted to a string by SQL functions...
You are seeing the a rendered, localised version of an internal date representation (numbers of days since 01 Jan 1900 basically).
Don't worry about it. You'll get date back to your client (in an internal date representation) and this can be formatted how you like there.
Store the data normally. When you retrieve the data, do something like this on the code:
dateField.ToString("dd/MM/yyyy")
And your result will be: 11/04/2011
Maybe you can select that like this:
select CONVERT(varchar(12) , getdate(), 103 )

date format and regional settings

I'm using MS SQL 2000, VS2008, MVC and C#.
I'm trying to insert and update some data using stored procedures.
Some columns are of type datetime.
Regional settings on both server and client are set to Dutch (Belgium)
This means the default date format is dd/mm/yyyy.
When i try to insert or update with a date of eg. 28/03/2009, I get following errors:
Insert:
Error converting data type nvarchar to datetime
Update:
The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value
When I try with a date like 01/03/2009, I get no errors but the date is saved as 03/01/2009, which is the US date format.
This is typical behaviour for problems with regional settings. But both are set to Dutch (Belgium).
Why does it save dates in the US format?
What am i missing here?
Thanks!
Stijn
You should be inserting data into the database using a DateTime object, not a string. Your client-side code should convert the client's date entry to a DateTime object using the client's regional settings, then the DateTime struct should be added to the parameter that is ultimately sent into the database.
The SQL Instance has it's own locale setting, by default "us_english"
Now, this usually happens if you pushing using varchar rather than native datetime to store data values. If your code/tables use datetime columns and you define parameters as datetime then you won't get errors.
i had this problem too, its something to do with the date format for you SQL server,
i solved it by formatting the date string to be inserted like so
DateTime.Now.ToString("MM/dd/yyyy HH:mm")
hope that helps
All above suggestions are correct but I find if you are adding a datetime as a string/varchar the safest way is in the format 'YYYY-MM-DD'
So eg.
Update MyTable
Set MyDate = '2010-03-01'

SQL Server 2005 vs. ASP.net datetime format confusion

I've found a similar question on stack overflow, but it didn't really answer the question I have. I need to make sure that my asp.net application is formatting the date dd/mm/yyyy the same as my SQL Server 2005.
How do I verify the date culture (if that's what it's called) of the server matches how I've programmed my app? Are there specific database settings and OS settings? Is it table-specific? I don't want to transpose my days and months.
thank you
When you get a DateTime out of the database, it should be in a non-cultured format (like the DateTime object, based on the number of ticks since a certain date). It is only when you are converting that value into a string that you need to be concerned with culture. In those cases, you can use yourDateTimeValue.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture) to make sure that the information displays correctly.
I belive that if you use SqlParameters ADO.NET will take care of the rest and you don't have to worry about it. Besides, it's good for defending against SQL Injection attacks too! :)
** Watch out because SQL DateTime columns are non-nullable and their minimum value is 1/1/1753 while .net DateTimes are non-nullable with min values of 1/1/0001. **
If you're pulling data from a real DateTime column, by default it will always be in the same standard format. For saving the data to the column, you might want to specify the SqlDbType.DateTime in your parameter.
i ripped this off of http://bytes.com/forum/thread767920.html :
com.Parameters.Add("#adate", SqlDbType.DateTime).Value = DateTime.Now;
Well, if you keep datetime fields in the DB you shouldn't worry about it.
As long as you keep the dates in app strongly typed (DateTime variables) and send the dates through prepared statements with DBParameter/SqlParameter your DB will take them as is.
If you use strings to hold your dates in code, some casts will ensure you send the right values:
string sqlCmd = #"SELECT *
FROM MyTable
WHERE MyDateField = CONVERT(datetime, '{0}', 101)";
// assuming myDateString is a string with a date in the local format
sqlCmd = string.Format(sqlCmd,
Convert.ToDateTime(myDateString).ToString("yyyyMMdd"));
(the code is ugly, but hopefully it gets the point across)
As others have mentioned, you should be OK as far as storing datetimes culturally. What I would recommend is that you store all of your times as standard UTC time. In SQL Server 2005 and older there is no way to store time zone information, but if everything is stored in universal time, you should be OK because the time can be converted to the local time later on.
SQL Server 2008 does have some datatypes that are aware of time zones, and if you're using .NET 3.5 there are tools to assist with time zone handling/conversions.
Definitely keep times in universal format. This will make a world of a difference if you have to work in multiple time zones.

Resources