How to convert varchar date into datetime in sql - sql

I have varchar date in this format:
03/13/2015 : 2130
and i would like to convert it into datetime something like this:
2015-03-13 21:30:00.000
i have seen example like this but did not work for what i am looking for
DECLARE #Date char(8)
set #Date='12312009'
SELECT CONVERT(datetime,RIGHT(#Date,4)+LEFT(#Date,2)+SUBSTRING(#Date,3,2))

This will work assuming all date times parts are padded with 0's consistently.
DECLARE #Input VARCHAR(50);
SET #Input = '03/13/2015 : 2130';
SET #Input = LEFT(#Input, 10) + ' ' + LEFT(RIGHT(#Input, 4), 2) + ':' + RIGHT(RIGHT(#Input, 4), 2);
PRINT #Input;
PRINT CONVERT(DATETIME, #Input);
PRINT CONVERT(VARCHAR(50), CONVERT(DATETIME, #Input), 121);
Output:
03/13/2015 21:30
Mar 13 2015 9:30PM
2015-03-13 21:30:00.000

OP wants mmddyy and a plain convert will not work for that:
select convert(datetime,'12312009')
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
so try this:
DECLARE #Date char(8)
set #Date='12312009'
SELECT CONVERT(datetime,RIGHT(#Date,4)+LEFT(#Date,2)+SUBSTRING(#Date,3,2))
OUTPUT:
2009-12-31 00:00:00.000
(1 row(s) affected)

I think this is what you're looking for:
DECLARE #Date VARCHAR(20)
SET #Date = '03/13/2015 : 2130'
-- Format the date string
SET #Date = LEFT(#Date, 10) + ' ' + SUBSTRING(#Date, 14, 2) + ':' + SUBSTRING(#Date, 16, 2)
-- convert to date
Select CONVERT(varchar, CONVERT(DATETIME, #Date), 121)
SQL Fiddle
More Info

Sql Function:
CONVERT(data_type(length),expression,style)
you can try this:
CONVERT(datetime,#varCharDate,121)
For more see this link

If convert is not working for you then you can use mid to take date, month, year etc. And then use str_to_date to construct datetime in desired format.
In oracle use to_date and this stackoverflow link for taking substring

Related

How to read Date in 'Aug 02, 2021' format in SQL

I have Date stored in DB in format: '02/08/2021' (Date selected from mobile app). I want it to be stored/returned in format: Aug 02, 2021.
This is what I have tried:
declare #value Date = '02/08/2021'
select Convert(varchar(30), #value, 107)
But, I get error saying:
Conversion failed when converting date and/or time from character
string.
How can I fix this using SQL Query?
you may convert string first
DECLARE #s nvarchar(50) = '02/08/2021'
declare #value Date = SUBSTRING(#s,4,2) + '/' + SUBSTRING(#s,1,2) + '/' + SUBSTRING(#s,7,4)
select Convert(varchar(30), #value, 107)

How to convert a string into datetime in SQL Server?

I am writing a SQL query to convert string to datetime:
SELECT CAST('2017-04-07.15-23-44' AS datetime)
When I am converting it to datetime getting an error
varchar data type to datetime data type resulted in out of range value.
Split the string with the . as delimiter and in the 2nd part replace all '-' with ':'.
Concatenate the 2 parts again and then cast it to DATETIME:
DECLARE #d VARCHAR(20) = '2017-04-07.15-23-44';
SELECT CAST(LEFT(#d, CHARINDEX('.', #d) - 1) + ' ' +
REPLACE(SUBSTRING(#d, CHARINDEX('.', #d) + 1, LEN(#d)), '-', ':')
AS datetime
)
See the demo.
You can try the following to format as an ISO date
declare #date varchar(20)='2017-04-07.15-23-44'
select Cast(Replace(Replace(Stuff(Stuff(#date,14,1,':'),17,1,':'),'-',''),'.',' ') as datetime)

How to combine date with time, typed by hand in SQL Server?

I have date: '2015-01-01' and time: '15:01:45'
How to make it '2015-01-01 15:01:45' ?
This is my failed attempt:
SELECT CAST('2015-01-01' AS DATE) + CAST('10:21:38' AS TIME)
I get an error:
Msg 8117, Level 16, State 1, Line 1
Operand data type date is invalid for add operator.
As per your comment, you can concatenate the variable with space in between and CAST as datetime
DECLARE #Date AS VARCHAR (50) = '2015-01-01';
DECLARE #Time AS VARCHAR (50) = '10:21:38'
SELECT CAST(#Date + ' ' + #Time AS DATETIME) AS Result FROM ##x2
Try this:
SELECT cast(my_date + ' ' + my_time as datetime)

SQL Date/Time Format

How to convert date/time from 20150323153528 to 2015-03-23 15:35:28.000. I need this to filter based on the getdate(). Thanks in advance.
Select * from table
Where 20150323153528 > GETDATE() - 7
Statement to convert date to your requirement
DECLARE #Date varchar(20) = '20150323153528'
Select * from table Where
CONVERT(DATETIME, CONVERT(CHAR(8), #Date), 121) + ' ' + stuff(stuff(right('000000' + cast(#Date as varchar),6),5,0,':'),3,0,':') as DATETIME > GETDATE() - 7
In MS SQL you could use
DECLARE #Date varchar(20) = '20150323153528'
Select * from table Where CAST(convert(varchar,#Date) as datetime) > GETDATE() - 7
Please read this page.
SELECT convert(varchar, getdate(), 120) — yyyy-mm-dd hh:mm:ss(24h)
Note: I assume this is a Microsoft SQL Server environment using T-SQL:
The formatting of date / datetime values is not a concern of T-SQL. You should do that in your presentation-layer (i.e. your frontend code).
If you have date/time values represented as integers of the form 20150323153528 then you cannot use them in T-SQL. You need to convert them to strings (preferably in ISO-8601 format) for SQL Server to successfully internally convert them to datetime (or datetimeoffset) values which can then be compared with other datetime values.
I suggest performing the conversion in your application code before you send it to SQL, as a datetime-typed parameter value, like so:
Int32 weirdDateValue = 20150323153528;
String s = weirdDateValue.ToString( CultureInfo.InvariantCulture );
String dtValueAsIso8601 = String.Format("{0}-{1}-{2} {3}:{4}:{5}.{6}",
s.Substring(0, 4), s.Substring(4, 2), s.Substring(6, 2),
s.Substring(8, 2), s.Substring(10, 2), s.Substring(12, 2), s.Substring(14)
);
DateTime dtValue = DateTime.ParseExact( dtValueAsIso8601, "yyyy-MM-dd HH:mm:ss.fff" );
cmd.Parameters.Add("#dtValue", SqlDbType.DateTime).Value = dtValue;
In T-SQL the process is pretty much the same, except using MID - note that MID uses 1-based character indexes instead of 0-based:
DECLARE #input int = 20150323153528
DECLARE #s varchar( 14 ) = CONVERT( #input, nvarchar(14) )
DECLARE #dtStr varchar( 24 ) = MID( #s, 1, 2 ) + '-' + MID( #s, 3, 2 ) + '-' + MID( #s, 5, 2 ) + ' ' + -- etc...
DECLARE #dt datetime = CONVERT( #dtStr, datetime )
SELECT
*
FROM
[table]
WHERE
#dt > GETDATE() - 7
If the integer values are stored in an actual column instead of a parameter you'll need to convert the logic into a scalar UDF which performs the conversion. I strongly suggest you change the table's design to add a strongly-typed datetime column and permanently store the value there, and then drop the datetime-as-int column:
CREATE FUNCTION ConvertIntDateIntoDateTime(#dateAsInt int) RETURNS datetime AS
BEGIN
-- same code as above minus the SELECT statement
RETURN #dt
END
Used in an inner subquery to allow the data to be accessed in WHERE statements, like so:
SELECT
*
FROM
(
SELECT
*,
dbo.ConvertIntDateIntoDateTime( someDateColumn ) AS someDateColumn2
FROM
[table]
) AS FixedTable
WHERE
FixedTable.someDateColumn2 > GETDATE() - 7

How do I create a datetime from a custom format string?

I have datetime values stored in a field as strings. They are stored as strings because that's how they come across the wire and the raw values are used in other places.
For reporting, I want to convert the custom format string (yyyymmddhhmm) to a datetime field in a view. My reports will use the view and work with real datetime values. This will make queries involving date ranges much easier.
How do I perform this conversion? I created the view but can't find a way to convert the string to a datetime.
Thanks!
Update 1 -
Here's the SQL I have so far. When I try to execute, I get a conversion error "Conversion failed when converting datetime from character string."
How do I handle nulls and datetime strings that are missing the time portion (just yyyymmdd)?
SELECT
dbo.PV1_B.PV1_F44_C1 AS ArrivalDT,
cast(substring(dbo.PV1_B.PV1_F44_C1, 1, 8)+' '+substring(dbo.PV1_B.PV1_F44_C1, 9, 2)+':'+substring(dbo.PV1_B.PV1_F44_C1, 11, 2) as datetime) AS ArrDT,
dbo.MSH_A.MSH_F9_C2 AS MessageType,
dbo.PID_A.PID_F3_C1 AS PRC,
dbo.PID_A.PID_F5_C1 AS LastName,
dbo.PID_A.PID_F5_C2 AS FirstName,
dbo.PID_A.PID_F5_C3 AS MiddleInitial,
dbo.PV1_A.PV1_F2_C1 AS Score,
dbo.MSH_A.MessageID AS MessageId
FROM dbo.MSH_A
INNER JOIN dbo.PID_A ON dbo.MSH_A.MessageID = dbo.PID_A.MessageID
INNER JOIN dbo.PV1_A ON dbo.MSH_A.MessageID = dbo.PV1_A.MessageID
INNER JOIN dbo.PV1_B ON dbo.MSH_A.MessageID = dbo.PV1_B.MessageID
According to here, there's no out-of-the-box CONVERT to get from your yyyymmddhhmm format to datetime.
Your strategy will be parsing the string to one of the formats provided on the documentation, then convert it.
declare #S varchar(12)
set #S = '201107062114'
select cast(substring(#S, 1, 8)+' '+substring(#S, 9, 2)+':'+substring(#S, 11, 2) as datetime)
Result:
2011-07-06 21:14:00.000'
This first changes your date string to 20110706 21:14. Date format yyyymmdd as a string is safe to convert to datetime in SQL Server regardless of SET DATEFORMAT setting.
Edit:
declare #T table(S varchar(12))
insert into #T values('201107062114')
insert into #T values('20110706')
insert into #T values(null)
select
case len(S)
when 12 then cast(substring(S, 1, 8)+' '+substring(S, 9, 2)+':'+substring(S, 11, 2) as datetime)
when 8 then cast(S as datetime)
end
from #T
Result:
2011-07-06 21:14:00.000
2011-07-06 00:00:00.000
NULL
You can use CAST or CONVERT.
Example from the site:
G. Using CAST and CONVERT with
datetime data
The following example displays the
current date and time, uses CAST to
change the current date and time to a
character data type, and then uses
CONVERT display the date and time in
the ISO 8901 format.
SELECT
GETDATE() AS UnconvertedDateTime,
CAST(GETDATE() AS nvarchar(30)) AS UsingCast,
CONVERT(nvarchar(30), GETDATE(), 126) AS UsingConvertTo_ISO8601;
GO
Here is the result set.
UnconvertedDateTime UsingCast UsingConvertTo_ISO8601
----------------------- ------------------------------ ------------------------------
2006-04-18 09:58:04.570 Apr 18 2006 9:58AM 2006-04-18T09:58:04.570
(1 row(s) affected)
Generally, you can use this code:
SELECT convert(datetime,'20110706',112)
If you need to force SQL Server to use a custom format string, use the following code:
SET DATEFORMAT ymd
SELECT convert(datetime,'20110706')
A one liner:
declare #datestring varchar(255)
set #datestring = '201102281723'
select convert(datetime, stuff(stuff(#datestring,9,0,' '),12,0,':') , 112 )
Result:
2011-02-28 17:23:00.000
DECLARE #d VARCHAR(12);
SET #d = '201101011235';
SELECT CONVERT(SMALLDATETIME, STUFF(STUFF(#d,9,0,' '),12,0,':'));
Note that by storing date/time data using an inappropriate data type, you cannot prevent bad data from ending up in here. So it might be safer to do this:
WITH x(d) AS
(
SELECT d = '201101011235'
UNION SELECT '201101011267' -- not valid
UNION SELECT NULL -- NULL
UNION SELECT '20110101' -- yyyymmdd only
),
y(d, dt) AS
(
SELECT d,
dt = STUFF(STUFF(LEFT(d+'000000',12),9,0,' '),12,0,':')
FROM x
)
SELECT CONVERT(SMALLDATETIME, dt), ''
FROM y
WHERE ISDATE(dt) = 1 OR d IS NULL
UNION
SELECT NULL, d
FROM y
WHERE ISDATE(dt) = 0 AND d IS NOT NULL;
DECLARE #test varchar(100) = '201104050800'
DECLARE #dt smalldatetime
SELECT #dt = SUBSTRING(#test, 5, 2)
+ '/' + SUBSTRING(#test, 7, 2) + '/'
+ SUBSTRING(#test, 1, 4) + ' ' + SUBSTRING(#test, 9, 2)
+ ':' + SUBSTRING(#test, 11, 2)
SELECT #dt
Output:
2011-04-05 08:00:00