Convert day + time string to time - sql

I want to convert a column containing day hour minute and second to time (01 03:08:09) in SQL Server 2014 because it is in the nvarchar(255) data type, so that I can use the DATEDIFF function and I get an error message:
Conversion failed when converting date and/or time from character string.
I tried using;
SELECT CAST (Driver_at_restaurant_datetime AS time)
FROM deliveries
How do I resolve this?

01 03:08:09 is not a valid time, so it will produce an error. You need to extract 03:08:09 first with right() then convert it to a time as follows:
SELECT CAST (right(Driver_at_restaurant_datetime,8) AS time(0))
FROM deliveries

CONVERT(DATETIME,'1900-01-' + CONVERT(CHAR(2),CAST (LEFT(Driver_at_restaurant,2) AS INT) + 1) + RIGHT(Driver_at_restaurant,9),120)
This will convert your string to datetime and will let you apply datediff without loosing the "days" part.
The above implements ODBC cannonical style for convertion. More here:
https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver16
EDIT
Here's a more comprehensive example:
declare #testString1 nvarchar(30) = '00 17:47:12';
declare #testString2 nvarchar(30) = '01 03:08:09';
declare #testDate1 Datetime = CONVERT(DATETIME,'1900-01-' + CONVERT(CHAR(2),CAST (LEFT(#testString1,2) AS INT) + 1) + RIGHT(#testString1,9),120)
declare #testDate2 Datetime = CONVERT(DATETIME,'1900-01-' + CONVERT(CHAR(2),CAST (LEFT(#testString2,2) AS INT) + 1) + RIGHT(#testString2,9),120)
SELECT
#testDate1 AS TestDate1,
#testDate2 AS TestDate1,
DATEDIFF(MINUTE,#testDate1,#testDate2) AS DateDiff_Minutes,
DATEDIFF(HOUR,#testDate1,#testDate2) AS DateDiff_Hours,
DATEDIFF(DAY,#testDate1,#testDate2) AS DateDiff_Days

Related

SQL Convert data time format (yyyy-mm-dd 00:00:00.000) to yyyymmdd as int

It must be very simple, but I don't know SQL language very well.
I need to filter data by date which is in this format:
How to do it right to filter data this way?
FROM [TableName] where
FileDate>=20220505
I've already tried the command LEFT and CAST but with no success
Something like this may work:
declare #now Datetime = getdate();
declare #intNow int = cast(cast(datepart(year, #now) as varchar(4)) + RIGHT('00'+CAST(datepart(month, #now) AS VARCHAR(2)),2) + RIGHT('00'+CAST(datepart(day, #now) AS VARCHAR(2)),2) as int)
Although if you have your date to check against in the right format e.g. using:
declare #dateToCheck Datetime = cast(cast(20220505 as varchar) as datetime)
And then
FileDate>= #dateToCheck
it should work
You can create an integer representation of your datetime by multiplying and adding the date parts:
year * 10000 20220000
month * 100 500
day 5
-------------------------
20220505
...
FROM [TableName]
WHERE (DATEPART(year, [FileDate]) * 10000) + (DATEPART(month, [FileDate]) * 100) + (DATEPART(day, [FileDate])) >= 20220505
However I'd still look into fixing the condition input format instead.
Credit to #Rangani in Yesterday's date in SSIS package setting in variable through expression for "multiply and add instead of string concat" trick

String to Date in 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;

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)

How to convert nvarchar type to only time type format in sql server

I have a column of type nvarchar i.e 170948 I want to store it in time type column
For that I had written
select #CurrentTimeValue=Convert(time, items, 108) from T
but it is throwing error
Conversion failed when converting date and/or time from character string.
Please suggest the correct format
Since none of the supported CONVERT styles match your input, you'll have to tweak your input manually - something like this:
DECLARE #input VARCHAR(10) = '170948'
DECLARE #modified VARCHAR(10)
SET #modified = SUBSTRING(#input, 1, 2) + ':' + SUBSTRING(#input, 3, 2) + ':' + RIGHT(#input, 2)
SELECT CAST(#modified AS TIME)
You could also try
select cast(stuff(stuff('170948', 5,0,':'), 3,0,':') as time)
select cast(stuff(stuff('170948', 3,0,':'), 6,0,':') as time)

Convert CMMDDYY into date in SQL Server

If I have a date string in the format of CMMDDYY
C = 0, 1 or 2 where 0 represents 19, 1 represents 20 and 2 represents 21
Example:
1022511 would be 02/25/2011 in mm/dd/yyyy format.
Is there a way to convert this into mm/dd/yyyy format in sql server?
Is CMMDDYY even a valid date format? I haven't found much information on it.
The Year algorithm is simply: (19 + int(C))*100 + int(yy)
Try this:
declare #st nvarchar(7)
set #st = '1030609'
select
cast(
substring(#st,2,2) + '/'
+ substring(#st,4,2) + '/'
+ cast((19 + cast(substring(#st,1,1) as int) )* 100
+ cast(substring(#st,6,2) as int) as nvarchar)
as datetime)
This outputs:
It doesn't sound like a built in date format but you should be able to find it on msdn if it is. If not you could write a function in SQL server that parses a string in that format to a DateTime object