String to Date in SQL - sql

Is there a way to quickly convert this date format to DATE in SQL?
{ “date_from”:”22112017”,”date_to”:”22112017”}
This is needed to filter the data between these dates
(There are a lot of conversion entries on the web, but I haven't found that format)
EDIT:
DECLARE #EndDate DATE = CONVERT(VARCHAR, '22112017', 103)
PRINT #EndDate
Error: Conversion failed when converting date and/or time from character string.
WHAT I HAVE:
#StartDate = '22112017'
#EndDate = '22112020'
WHAT I NEED TO DO:
SELECT * from tblMy WHERE ReceivedDate BETWEEN #StartDate AND #EndDate

If you fix your JSON to not use stylised double quotes (”) and use standard ones (") then you can parse this as JSON. Once you extract the values, you can inject a couple of / characters in and then convert to a date with the style code 103 (dd/MM/yyyy):
DECLARE #String nvarchar(MAX) = N'{ "date_from":"22112017","date_to":"22112017"}';
SELECT CONVERT(date,STUFF(STUFF(OJ.date_from,5,0,'/'),3,0,'/'),103) AS date_from,
CONVERT(date,STUFF(STUFF(OJ.date_to,5,0,'/'),3,0,'/'),103) AS date_to
FROM (VALUES(#String))V(S)
CROSS APPLY OPENJSON(V.S)
WITH (date_from varchar(8),
date_to varchar(8)) OJ;
Edit:
Seems the OP has moved their goal posts, this has nothing to do with JSON.
The problem here is your literal strings. When using literal strings for a date and time data type use either yyyyMMdd or yyyy-MM-ddThh:mm:ss.nnnnnnn as they are both unambiguous regardless of language and data type:
DECLARE #StartDate date,
#EndDate date;
SET #StartDate = '20171222';
SET #EndDAte = '20201122';
SELECT *
FROM tblMy
WHERE ReceivedDate BETWEEN #StartDate AND #EndDate;

I would suggest converting the value to a standard SQL Server date value. This is pretty simple:
select convert(date, left(val, 4) + substring(val, 3, 2) + right(val, 2))
The standard date format is YYYYMMDD. Yours is DDMMYYYY, so string operations can convert it to the correct format. Of course, what you should probably do is to convert the value to a date in the application layer and pass the date value in as a parameter.

This should fix the error "Error: Conversion failed when converting date and/or time from character string."
DECLARE #EndDate VARCHAR(MAX) = '22112017'
DECLARE #datevar date = CAST(SUBSTRING(#EndDate, 3, 2) + '/' + SUBSTRING(#EndDate,
1, 2) + '/' + SUBSTRING(#EndDate, 5, 4) AS date);
SELECT #datevar;

Related

Error converting data type varchar to date converting an int year into a string

I have SchoolYear variable as an INT, and I'm trying to set a variable to this:
SET #BeginDate = '07/01/' + CONVERT(VARCHAR(4), #SchoolYear - 1)
It gives me the 'Error converting data type varchar to date' error.
Example:
#SchoolYear INT = 2019,
#BeginDate Date - NULL
Desired result:
07/01/2018
What am I doing wrong please?
Check out DATEFROMPARTS (available from SQL 2012), and bypass strings altogether.
SET #BeginDate = DATEFROMPARTS(#SchoolYear - 1, 1, 7)
1st arg = year, 2nd = month, 3rd = day.
The format you are using is simply not understood by your sql server.
When dealing with dates in varchar columns/variables it is best to use a date format that is language neutral.
yyyyMMdd is such a format, it will always work no matter what regional settings are used on your server.
See also this http://karaszi.com/the-ultimate-guide-to-the-datetime-datatypes
in your case you should use
SET #BeginDate = CONVERT(VARCHAR(4), #SchoolYear - 1) + '0107'
that is assuming that 01 is the month, and 07 is the day so you end up with 20180107
Better would be off course to avoid varchar complete when converting, like this
set #BeginDate = DATEFROMPARTS(#SchoolYear - 1, 1, 7)
Maybe you should use the yyyy-mm-dd format and change the set as:
SET #BeginDate = CONVERT(VARCHAR(4), #SchoolYear - 1)+ '-01-07'
Declare #SchoolYear int
Set #SchoolYear = 2019
Declare #BeginDate varchar(50)
SET #BeginDate = '07/01/' + CONVERT(VARCHAR(4), #SchoolYear - 1)
--Once You have you varchar populated, you can use Convert Function to convert
--to datetime and select the format you want
Select CONVERT (Datetime,#BeginDate, 101)

SQL date conversion HHMMSS.CCCNNNNNN to yyyy-mm-dd hh:mi:ss.mmm

I have data in this format : 114643.052303537 (HHMMSS.CCCNNNNNN).
I need to convert it to this format : 2018-04-25 12:40:59.573 (yyyy-mm-dd hh:mi:ss.mmm), strip of the date part ( i.e. 2018-04-25 ) and calculate the time difference between two formats.
Could you please help with this?
I need the time difference in hh:mi:ss.mmm format
The way to get this is to convert BOTH values to milliseconds (looking at only the time portion for the value that has a date); calculate the difference with simple subtraction, and then convert the result to hh:mi:ss.mmm with division and modulo operations.
declare #dt datetime = '2018-04-25 12:40:59.573'
declare #dunno varchar(16) = '114643.052303537'
Strip the date off the datetime and give it today's date
getdate() + right(convert(varchar,#dt,113),12)
Convert the varchar to time and give it today's date
getdate() + left(stuff(stuff(#dunno,3,0,':'),6,0,':'),8)
Find the milliseconds between them
datediff(millisecond,getdate() + left(stuff(stuff(#dunno,3,0,':'),6,0,':'),8),getdate() + right(convert(varchar,#dt,113),12))
Put it all together in your format
select
convert(char(13),
dateadd(millisecond,
datediff(millisecond,getdate() + left(stuff(stuff(#dunno,3,0,':'),6,0,':'),8),getdate() + right(convert(varchar,#dt,113),12)),
'01/01/00'),
14)
Depending on the speed of your server and other code, it'd be wise to use a variable for GETDATE() at the beginning to prevent millisecond, or even second differences during conversion.
declare #dt datetime = '2018-04-25 12:40:59.573'
declare #dunno varchar(16) = '114643.052303537'
declare #today datetime = getdate()
declare #dunno2 datetime
declare #dt2 datetime
set #dt2 = #today + right(convert(varchar,#dt,113),12)
set #dunno2 = #today + left(stuff(stuff(#dunno,3,0,':'),6,0,':'),8)
select
convert(char(13),
dateadd(millisecond,
datediff(millisecond,#dunno2,#dt2),
'01/01/00'),
14)

convert varchar(ddmmyyyy) to date format

How can I convert, for example, ddmmyyyy which is a varchar(8) to date format(dd/mm/yyyy)?
I have a stored procedure which accepts a date varchar(8) parameter.
I want to convert it to date format before inserting into database.
I tried to use
INSERT INTO mytable(createdDate) VALUES (CONVERT(date, CONVERT(varchar(8), #date), 106));
An error:
Conversion failed when converting date and/or time from character string.
createdDate column is type : date
ddmmyyyy is not a valid date format. You need to first make that string into something that can be parsed as a DATE / DATETIME. The quickest way might be to simply SUBSTRING the pieces into a mm/dd/yyyy format. That does convert successfully. But you have a VARCHAR(8). So you either need to increase that to be VARCHAR(10) (or better yet, just CHAR(10)), or declare a local variable to hold the altered value.
For example:
DECLARE #Date VARCHAR(8); -- input parameter
SET #Date = '25032014';
DECLARE #Date2 CHAR(10);
SET #Date2 = SUBSTRING(#Date, 3, 2)
+ '/' + SUBSTRING(#Date, 1, 2)
+ '/' + SUBSTRING(#Date, 5, 4);
SELECT #Date2, CONVERT(DATE, #Date2);
-- 03/25/2014 2014-03-25
EDIT:
Actually, I found a slightly simpler way. I started out with this method but realized that it did not work with ddmmyyyy as opposed to mmddyyyy. I somehow missed that there was an appropriate date style number for dd/mm/yyyy. So, simply adding two slashes to the incoming string and then calling CONVERT does work, but only if you use 103 as the "style". And like the first solution, it requires either changing the incoming parameter to be VARCHAR(10) or CHAR(10) instead of VARCHAR(8), or creating a local variable to be CHAR(10).
DECLARE #Date VARCHAR(8); -- input parameter
SET #Date = '25032014';
DECLARE #Date2 CHAR(10);
SET #Date2 = STUFF(STUFF(#Date, 3, 0, '/'), 6, 0, '/');
SELECT #Date2, CONVERT(DATE, #Date2, 103); -- 103 = dd/mm/yyyy
-- 25/03/2014 2014-03-25
Conversion "styles" can be found on the MSDN page for CAST and CONVERT.

Char to DateTime Conversion

I have one column capturedatetime(Char(30)):
2006-04-25T15:50:59.997000 PM
And I want to convert it and load it at other table column which have is in DateTime. either by T-sql or SSIS which ever way.
I have tried with:
select CONVERT(datetime, '2006-04-25T15:50:59.997000 PM', 126)
But it creates an error:
Conversion failed when converting date and/or time from character string
Late update:
In this column I also have other data that is in a completely different format:
29-JAN-10 08.57.41.000000 PM
(1) STOP storing datetime data in string columns! This is nothing, nothing, nothing but trouble.
(2) Why on earth does your column get data in two different string formats that aren't even valid? Why does the string use 24 hour time and have AM/PM suffix? Why use a regional string format and Y2K disaster like 29-JAN-10?
Here is one way, but it's awfully ugly. I highly recommend you fix the SSIS process to give you valid datetime values in the first place, if not as datetimes, at least as valid ISO strings (yyyy-mm-ddThh:mm:ss.nnn):
DECLARE #x TABLE (d CHAR(30));
INSERT #x SELECT '2006-04-25T15:50:59.997000 PM'
UNION ALL SELECT '29-JAN-10 08.57.41.000000 PM';
SET LANGUAGE ENGLISH; -- this is important, else style 6 may not work
SELECT
CASE WHEN d LIKE '__[0-9]%' THEN
CONVERT(DATETIME, LEFT(d, 23))
WHEN d LIKE '[0-9][0-9]-%' THEN
CONVERT(DATETIME, CONVERT(CHAR(8),
CONVERT(DATETIME,REPLACE(LEFT(d,9),' ','-'),6),112)
+ ' ' + REPLACE(SUBSTRING(d,11,8),'.',':')
+ ' ' + RIGHT(RTRIM(d),2))
END
FROM #x;
The conversion for 126 requires no spaces ... I've got it to work like this:
declare #T varchar(50)
declare #dt datetime
set #T = '2006-04-25T15:50:59.997'
set #dt = convert(datetime,#t,126)
select #T, #dt
select convert(datetime,left('2006-04-25T15:50:59.997000 PM',23))
or
select convert(datetime,left(capturedatetime,23))
If you use cast, you do not even need to supply a format. Code snippet below tested on SQL 2012 Developer version.
declare #var_string varchar(50) = '2006-04-25T15:50:59.997';
declare #var_datetime datetime = cast(#var_string as datetime);
select #var_string as my_string, #var_datetime as my_variable;

Conversion failed converting datetime from string

I am trying to convert my three parameters to a DATETIME but its not working. I get the error that the conversion failed when converting datetime from character string whenever I run this query. Perhaps I am doing in wrong in the conversion? If anyone can provide any feedback.
#month varchar,
#day varchar,
#year varchar
AS
DECLARE #date DATETIME
SET #date = Convert(DateTime, #month + '/' + #day + '/' + #year, 101)
Select *
From events
Where (EDate = #date) OR EDateEnd = #date OR #date Between EDate AND EDateEnd
Order By EDate ASC
You need to set the size of your parameters. Probably something like
#month varchar(2),
#day varchar(2),
#year varchar(4)
That should be working. Make sure you have provided valid values in you parameters.
Update
You should lose the 101 parameter for conversion. Provided that parameters are informed with valid values, this should work for both 2-digit and 4-digit years:
SET #date = Convert(DateTime, #month + '/' + #day + '/' + #year)
This is just a guess, because the conversion function shown should work with the proper parameters.
Are you passing in the year as a two-digit number? If so, try passing it as the full four digit year (which the "101" format expects) OR change it to
SET #date = Convert(DateTime, #month + '/' + #day + '/' + #year, 1)
if you're passing in a 2 digit year.
(See the difference for with century and without century here: http://msdn.microsoft.com/en-us/library/ms187928.aspx)
EDIT
I have a second guess... The error may not be on the line where you're explicitly converting the parameters into a Datetime variable. This has burned me before... The error MAY be occurring on the following line:
Where (EDate = #date) OR EDateEnd = (#date) OR #date Between EDate AND EDateEnd
if the EDate column or EDateEnd column is not necessaryly a DateTime column. It could be that THOSE contain the values that can't be converted to a DateTime. (They could be char fields, with a DateTime string stored in them, or they could be actual Date fields with null values stored in them.)
However, without more information about the actual schema of the database it's hard to tell. The best we can do is guess.