SQL Server ODBC canonical date format to DD/MM/YYYY? - sql-server

Lets say I have a datetime from my database, such as: 2011-10-24 00:00:00.000. I would like to convert this into 24/10/2011, but I can't find the native SQL Server way to do this, and I'd rather no do this in the code after I run my query.
I've tried doing something as follows (as per the manual)
select CONVERT(datetime, '2011-10-24 00:00:00.000', 103);
But that doesn't work out, my result is:
Msg 242, Level 16, State 3, Line 1
The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
I suspect this might be due to the decimal precision, or the time part of this, but I'm not sure how to go about this without resulting to some string-hacking-regex-replace nonsense (and I'd rather no do that, I might as well end up doing the conversion after the query if I do that).

If I read the manual correctly, you should be using stlye 120 "ODBC canonical" - no??
Try:
select CONVERT(datetime, '2011-10-24 00:00:00.000', 120);
Works on my machine :-) This gives you a SQL Server DATETIME to work with.
If you want to convert that further into 24/10/2011, use a second CONVERT to convert into a VARCHAR string:
select CONVERT(VARCHAR(50), CONVERT(datetime, '2011-10-24 00:00:00.000', 120), 103)
That gives me:
24/10/2011

Related

sql server convert function behave differently on different machine

When I run this query on one machine it works perfectly:
select convert(datetime, '2021-01-18 00:00:00.000')
But in another machine, I get an out of range error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
That format is invalid when using certain language and dateformat settings. Example db<>fiddle and another example.
SET DATEFORMAT YDM;
SELECT CONVERT(datetime, '2021-01-18 00:00:00.000');
..or...
SET LANGUAGE BRITISH;
SELECT CONVERT(datetime, '2021-01-18 00:00:00.000');
Both yield:
Msg 242 Level 16 State 3
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
You do not need to reinstall SQL Server to fix this, as it's not the installation that is the problem.
The real solution is to always use a safe, unambiguous format - see the links in the "Regional formats" section of Dating Responsibly.
These all succeed, for example:
SET DATEFORMAT YDM;
SELECT CONVERT(datetime, '2021-01-18T00:00:00.000');
SELECT CONVERT(datetime, '20210118 00:00:00.000');
SELECT CONVERT(datetime, '20210118');
...and...
SET LANGUAGE BRITISH;
SELECT CONVERT(datetime, '2021-01-18T00:00:00.000');
SELECT CONVERT(datetime, '20210118 00:00:00.000');
SELECT CONVERT(datetime, '20210118');
If you can't control the format of the string, then another option is to manually apply these settings first (this should work on whatever machine it's currently failing for you):
SET DATEFORMAT YMD;
SET LANGUAGE us_english;
SELECT CONVERT(datetime, '2021-01-18 00:00:00.000');
This is obviously not the optimal solution.
The issue may also be that the login connecting to the server with wrong results has their default language set to something other than the default US English (more than half of the languages SQL Server supports interpret yyyy-mm-dd as yyyy-dd-mm, for reasons I will never understand).
If this is the case, you may be able to fix this login...
ALTER LOGIN [login name] WITH DEFAULT_LANGUAGE = [us_english];
...but unless you are switching from british, this will have other consequences for them, such as language of warnings and errors, interpretation of other data like numeric, and so on. It also won't last if the login changes their setting back, and it won't affect any future logins that are created with a non-default language (or any logins that later change in the "wrong" direction).
So I still feel like fixing the way the ambiguous string is interpreted is not the answer.
In the comment you say you have code that does this:
WHERE datetime_col >= '2018-01-12'
In which case you can either:
(a) convert to datetime with the 120 style, overriding regional/language settings:
WHERE datetime_col >= CONVERT(datetime, '2018-01-12', 120)
(b) convert to date, which doesn't care about regional/language settings:
WHERE datetime_col >= CONVERT(date, '2018-01-12')
(c) I still think the best (and easiest!) answer is to simply not use an ambiguous format that requires workarounds and/or every login to be created a specific way and never override session settings:
WHERE datetime_col >= '20180112'

Convert UTC to EST in Query [MS SQL]

Long time reader first time poster :)
I am making a query that has a date formatted like this 2022-03-01T04:59:59.000+0000 since this is in UTC I need to get it into EST. I am having issues converting this. I have tried a few things I found online. The closest I have gotten is this.
SELECT CONVERT(datetime,
SWITCHOFFSET(CONVERT(datetimeoffset,
convert(varchar, [UTC Date Field], 1)),
DATENAME(TzOffset, SYSDATETIMEOFFSET())))
AS ColumnInLocalTime
from [Table Name] a (nolock)
But this is giving me an Conversion failed when converting date and/or time from character string. error. I am using MS SQL Server and I would consider my self competent in SQL. I know the data in the field I am using is stored as varchar. Any help would be appreciated.
Your value is not in a ISO8601 format that SQL Server recognizes, it's missing a : in the time zone part.
Let's just say you wouldn't have had this issue if your data would have been stored as datetimeoffset in the first place.
You can patch it up using STUFF, then just CONVERT with style 126
SELECT
SWITCHOFFSET(
CONVERT(datetimeoffset,
STUFF('2022-03-01T04:59:59.000+0000', 27, 0, ':'),
126),
DATENAME(TzOffset, SYSDATETIMEOFFSET())
)
db<>fiddle

How to convert it to a date format in SQL Server

I am trying to convert this time 2021-08-16 12:58:00.000 to a DateTime this way:
SELECT Convert(datetime, '16/08/2021 12:58:00:000PM');
And getting "Msg 242, Level 16, State 3, Line 1
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.".
What am I doing wrong? Is it an invalid date time?
The issue is that your date is formatted at dd/mm/yyyy and SQL Server expects it as mm/dd/yyyy. In fact, if you do this it will succeed:
SELECT CONVERT(datetime, '08/16/2021 12:58:00:000PM');
To make it work for your format, you need to pass a style value to let SQL Server know the format you are using. For your example, this works:
SELECT CONVERT(datetime, '16/08/2021 12:58:00:000PM', 103);
103 corresponds to dd/mm/yyyy. You can see a full list of style values in the documentation at https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver15

Using Parameters in DATEADD function of a Query

I am trying to us the DateAdd function of SQL in my Query. The problem is when I use a parameter to set the second arguement, the number argument I get an error which will say something like this:
Failed to convert parameter value from
a Decimal to a DateTime
While if I enter it parameterless, i.e hardcode an Int, it works fine.
This works:
SELECT FieldOne, DateField
FROM Table
WHERE (DateField> DATEADD(day, -10, GETDATE()))
while this does not:
SELECT FieldOne, DateField
FROM Table
WHERE (DateField> DATEADD(day, #days, GETDATE()))
Where #days = -10
Any ideas into what I am doing wrong? Incidentally I am setting this variable in SQL Server Manager, as I am trying to work out a bug in my DataAccess code. Not sure if that makes a difference.
Thanks
I know this is an old post, but for anyone else having this problem I had a similar issue in Reporting Services 2008 R2, although the error message was "Argument data type nvarchar is invalid for argument 2 of dateadd function." I think this issue could be related.
The problem was caused by the way Reporting Services parses the SQL code to generate a report dataset. In my case, I was able to change this dataset query:
SELECT DateAdd(wk, #NumWeeks, calendar_date) AS ToWeekFromDate
FROM dim_date
to this:
SELECT DateAdd(wk, Convert(Int, #NumWeeks), calendar_date) AS ToWeekFromDate
FROM dim_date
and the error was resolved.
EDIT: Just to expand on this answer a little: the issue was that Reporting Services was unable to parse the correct data type for #NumWeeks, I think possibly due to it being inside the DateAdd() function, and was defaulting it to NVarchar. Adding an explicit Convert() to set the data type to Int (even though it was already a number) enabled the parser to correctly identify the data type for #NumWeeks.
It sounds like you're passing the decimal as the 3rd instead of the 2nd parameter to DATEADD(), like:
DATEADD(day, GETDATE(), #days)
Although the snippet in the question looks fine.
(For extra clarity, the snippet above is an error. This is the code that would generate the error from the question.)
The following code works perfectly fine here (SQL Server 2005, executed in Management Studio):
DECLARE #days decimal
SET #days = -10
SELECT DATEADD(day, #days, GETDATE())
as does the following
DECLARE #days decimal
SET #days = -10
SELECT * FROM myTable WHERE myDate > DATEADD(day, #days, GETDATE())
So, the problem must lie somewhere else...
Are you sure the error is associated with this statement? There are no decimals involved and if I try this it still works
DECLARE #days decimal (19,6)
SET #days = -10.3346
--result is actually irrelevant
IF CAST(40000.6 AS decimal (19,6)) > DATEADD(day, #days, GETDATE())
SELECT 'yes'
ELSE
SELECT 'no'
Even trying to cast -10 decimal to smalldatetime this gives a different error
SELECT CAST(CAST(-10 AS decimal (19,6)) AS smalldatetime)
Msg 8115, Level 16, State 2, Line 1
Arithmetic overflow error converting expression to data type smalldatetime.

Sql Server string to date conversion

I want to convert a string like this:
'10/15/2008 10:06:32 PM'
into the equivalent DATETIME value in Sql Server.
In Oracle, I would say this:
TO_DATE('10/15/2008 10:06:32 PM','MM/DD/YYYY HH:MI:SS AM')
This question implies that I must parse the string into one of the standard formats, and then convert using one of those codes. That seems ludicrous for such a mundane operation. Is there an easier way?
Try this
Cast('7/7/2011' as datetime)
and
Convert(DATETIME, '7/7/2011', 101)
See CAST and CONVERT (Transact-SQL) for more details.
Run this through your query processor. It formats dates and/or times like so and one of these should give you what you're looking for. It wont be hard to adapt:
Declare #d datetime
select #d = getdate()
select #d as OriginalDate,
convert(varchar,#d,100) as ConvertedDate,
100 as FormatValue,
'mon dd yyyy hh:miAM (or PM)' as OutputFormat
union all
select #d,convert(varchar,#d,101),101,'mm/dd/yy'
union all
select #d,convert(varchar,#d,102),102,'yy.mm.dd'
union all
select #d,convert(varchar,#d,103),103,'dd/mm/yy'
union all
select #d,convert(varchar,#d,104),104,'dd.mm.yy'
union all
select #d,convert(varchar,#d,105),105,'dd-mm-yy'
union all
select #d,convert(varchar,#d,106),106,'dd mon yy'
union all
select #d,convert(varchar,#d,107),107,'Mon dd, yy'
union all
select #d,convert(varchar,#d,108),108,'hh:mm:ss'
union all
select #d,convert(varchar,#d,109),109,'mon dd yyyy hh:mi:ss:mmmAM (or PM)'
union all
select #d,convert(varchar,#d,110),110,'mm-dd-yy'
union all
select #d,convert(varchar,#d,111),111,'yy/mm/dd'
union all
select #d,convert(varchar,#d,12),12,'yymmdd'
union all
select #d,convert(varchar,#d,112),112,'yyyymmdd'
union all
select #d,convert(varchar,#d,113),113,'dd mon yyyy hh:mm:ss:mmm(24h)'
union all
select #d,convert(varchar,#d,114),114,'hh:mi:ss:mmm(24h)'
union all
select #d,convert(varchar,#d,120),120,'yyyy-mm-dd hh:mi:ss(24h)'
union all
select #d,convert(varchar,#d,121),121,'yyyy-mm-dd hh:mi:ss.mmm(24h)'
union all
select #d,convert(varchar,#d,126),126,'yyyy-mm-dd Thh:mm:ss:mmm(no spaces)'
In SQL Server Denali, you will be able to do something that approaches what you're looking for. But you still can't just pass any arbitrarily defined wacky date string and expect SQL Server to accommodate. Here is one example using something you posted in your own answer. The FORMAT() function and can also accept locales as an optional argument - it is based on .Net's format, so most if not all of the token formats you'd expect to see will be there.
DECLARE #d DATETIME = '2008-10-13 18:45:19';
-- returns Oct-13/2008 18:45:19:
SELECT FORMAT(#d, N'MMM-dd/yyyy HH:mm:ss');
-- returns NULL if the conversion fails:
SELECT TRY_PARSE(FORMAT(#d, N'MMM-dd/yyyy HH:mm:ss') AS DATETIME);
-- returns an error if the conversion fails:
SELECT PARSE(FORMAT(#d, N'MMM-dd/yyyy HH:mm:ss') AS DATETIME);
I strongly encourage you to take more control and sanitize your date inputs. The days of letting people type dates using whatever format they want into a freetext form field should be way behind us by now. If someone enters 8/9/2011 is that August 9th or September 8th? If you make them pick a date on a calendar control, then the app can control the format. No matter how much you try to predict your users' behavior, they'll always figure out a dumber way to enter a date that you didn't plan for.
Until Denali, though, I think that #Ovidiu has the best advice so far... this can be made fairly trivial by implementing your own CLR function. Then you can write a case/switch for as many wacky non-standard formats as you want.
UPDATE for #dhergert:
SELECT TRY_PARSE('10/15/2008 10:06:32 PM' AS DATETIME USING 'en-us');
SELECT TRY_PARSE('15/10/2008 10:06:32 PM' AS DATETIME USING 'en-gb');
Results:
2008-10-15 22:06:32.000
2008-10-15 22:06:32.000
You still need to have that other crucial piece of information first. You can't use native T-SQL to determine whether 6/9/2012 is June 9th or September 6th.
SQL Server (2005, 2000, 7.0) does not have any flexible, or even non-flexible, way of taking an arbitrarily structured datetime in string format and converting it to the datetime data type.
By "arbitrarily", I mean "a form that the person who wrote it, though perhaps not you or I or someone on the other side of the planet, would consider to be intuitive and completely obvious." Frankly, I'm not sure there is any such algorithm.
Use this:
SELECT convert(datetime, '2018-10-25 20:44:11.500', 121) -- yyyy-mm-dd hh:mm:ss.mmm
And refer to the table in the official documentation for the conversion codes.
For this problem the best solution I use is to have a CLR function in Sql Server 2005 that uses one of DateTime.Parse or ParseExact function to return the DateTime value with a specified format.
Short answer:
SELECT convert(date, '10/15/2011 00:00:00', 101) as [MM/dd/YYYY]
Other date formats can be found at SQL Server Helper > SQL Server Date Formats
Took me a minute to figure this out so here it is in case it might help someone:
In SQL Server 2012 and better you can use this function:
SELECT DATEFROMPARTS(2013, 8, 19);
Here's how I ended up extracting the parts of the date to put into this function:
select
DATEFROMPARTS(right(cms.projectedInstallDate,4),left(cms.ProjectedInstallDate,2),right( left(cms.ProjectedInstallDate,5),2)) as 'dateFromParts'
from MyTable
The most upvoted answer here are guravg's and Taptronic's. However, there's one contribution I'd like to make.
The specific format number they showed from 0 to 131 may vary depending on your use-case (see full number list here), the input number can be a nondeterministic one, which means that the expected result date isn't consistent from one SQL SERVER INSTANCE to another, avoid using the cast a string approach for the same reason.
Starting with SQL Server 2005 and its compatibility level of 90,
implicit date conversions became nondeterministic. Date conversions
became dependent on SET LANGUAGE and SET DATEFORMAT starting with
level 90.
Non deterministic values are 0-100, 106, 107, 109, 113, 130. which may result in errors.
The best option is to stick to a deterministic setting, my current preference are ISO formats (12, 112, 23, 126), as they seem to be the most standard for IT people use cases.
Convert(varchar(30), '210510', 12) -- yymmdd
Convert(varchar(30), '20210510', 112) -- yyyymmdd
Convert(varchar(30), '2021-05-10', 23) -- yyyy-mm-dd
Convert(varchar(30), '2021-05-10T17:01:33.777', 126) -- yyyy-mm-ddThh:mi:ss.mmm (no spaces)
This page has some references for all of the specified datetime conversions available to the CONVERT function. If your values don't fall into one of the acceptable patterns, then I think the best thing is to go the ParseExact route.
Personally if your dealing with arbitrary or totally off the wall formats, provided you know what they are ahead of time or are going to be then simply use regexp to pull the sections of the date you want and form a valid date/datetime component.
If you want SQL Server to try and figure it out, just use CAST
CAST('whatever' AS datetime)
However that is a bad idea in general. There are issues with international dates that would come up. So as you've found, to avoid those issues, you want to use the ODBC canonical format of the date. That is format number 120, 20 is the format for just two digit years.
I don't think SQL Server has a built-in function that allows you to provide a user given format. You can write your own and might even find one if you search online.
convert string to datetime in MSSQL implicitly
create table tmp
(
ENTRYDATETIME datetime
);
insert into tmp (ENTRYDATETIME) values (getdate());
insert into tmp (ENTRYDATETIME) values ('20190101'); --convert string 'yyyymmdd' to datetime
select * from tmp where ENTRYDATETIME > '20190925' --yyyymmdd
select * from tmp where ENTRYDATETIME > '20190925 12:11:09.555'--yyyymmdd HH:MIN:SS:MS
You can easily achieve this by using this code.
SELECT Convert(datetime, Convert(varchar(30),'10/15/2008 10:06:32 PM',102),102)
This code solve my problem :
convert(date,YOUR_DATE,104)
If you are using timestamp you can you the below code :
convert(datetime,YOUR_DATE,104)
dateadd(day,0,'10/15/2008 10:06:32 PM')

Resources