How to convert a string into datetime in SQL Server? - sql

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)

Related

Need to format date in SQL from string using charindex

I am trying to format a date in mm/dd/yyyy from string data using charindex, the date in the string is yyyymmdd. I have tried using convert, cast, castconvert.
If anyone could help that would be great! I have sample code
CONVERT (
VARCHAR (10)
, CASE
WHEN CHARINDEX ('^3507=', reg.BetaRequestString) = 0 THEN
''
ELSE
RIGHT(LEFT(reg.BetaRequestString, CHARINDEX ('^3507=', reg.BetaRequestString) + 13), 8)
END
, 101
declare #a nvarchar(10)
set #a='20180203'
select
convert(nvarchar(10),substring(#a,5,2)+'/'+substring(#a,7,2)+'/'
+substring(#a,1,4),101)
It appears you want this:
CASE WHEN CHARINDEX ('^3507=', reg.BetaRequestString) = 0
THEN ''
ELSE CONVERT(VARCHAR(10),RIGHT(LEFT(reg.BetaRequestString, CHARINDEX ('^3507=', reg.BetaRequestString) + 13), 8), 101)
END
When you know your input date format , you can split the parts and reorganise the date.
declare #date varchar(100)='20021230' ,
#Year int,#month int ,#day int
select #year=Substring(#date,1,4) ,#month=SUBSTRING(#date,5,2),#day=SUBSTRING(#date,7,2)
select convert(VARCHAR(10),(DATEFROMPARTS(#year,#month,#day)),101)
output-12/30/2002
You can also use datetime style in convert function:
https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql#date-and-time-styles
DECLARE #yyyymmdd sysname = '20180101'
SELECT CONVERT(sysname, CONVERT(datetime, #yyyymmdd, 112), 101)

How can I handle a SQL query by using convert decimal string to datetime in SQL Server?

I am trying to convert a decimal string to datetime:
20160709.0000000 => 09-07-2016 (dd-MM-YYYY)
but the code here returns an error:
Conversion failed when converting date and/or time from character string
Code:
select
CONVERT(DATETIME, CONVERT(nvarchar(50), MyBirthDate), 112) BirthDate, Test, Test2
from
tbl
This code also does not work:
select
CONVERT(DATETIME, CONVERT(VARCHAR(50), '20160709.0000000'), 112)
The unseparated format you show (yyyymmdd) will be casted implicitly. I hope I do understand your convert decimal string correctly. Assuming, the value is of string type, you can cast this directly, just cut off the part you need:
DECLARE #s VARCHAR(100)='20160709.0000000';
SELECT CAST(LEFT(#s,8) AS DATETIME);
The result
2016-07-09 00:00:00.000
Hint
This solution would just work the same with the argument as decimal value, due to the implicit cast to string while passing into LEFT:
DECLARE #s DECIMAL(20,10)=20160709.0000000;
SELECT CAST(LEFT(#s,8) AS DATETIME);
At first you need to convert string to int or else you can use replace function
SELECT CONVERT(DATETIME, REPLACE('20160709.0000000', '.0000000', ''))
or
SELECT CONVERT(DATETIME, CONVERT(VARCHAR(50), CAST(20160709.0000000 AS INT )), 112)
or
SELECT CONVERT(DATETIME, CONVERT(VARCHAR(50), CAST(20160709.0000000 AS INT )))
SELECT CONVERT(DATETIME, CONVERT(VARCHAR(50), CAST(20160709.0000000 AS INT )), 112)

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

ddmmyyyy to sql datetime in SQL

I need to convert a nvarchar value to datetime in T-SQL. The value is in ddmmyyyy format, e.g. 23072009
I need to convert to datetime in T-SQL.
I tried
select convert(datetime, '23072009', 103)
But it is throwing error.
"The conversion of a nvarchar data type to a datetime data type
resulted in an out-of-range value."
Any idea
Thanks
Rebuild your format to yyyymmdd.
declare #D varchar(8)
set #D = '23072009'
select cast(right(#D, 4)+substring(#D, 3, 2)+left(#D, 2) as datetime)
The style 103 will accept strings with dd/mm/yyyy format. So your code should be
declare #date varchar(8)
set #date='23072009'
select convert(datetime,stuff(stuff(#date,5,0,'/'),3,0,'/') , 103)
You can define custom function like this:
CREATE FUNCTION [dbo].[GetCustomDate] (#customDateString NVARCHAR(MAX))
RETURNS DATETIME
AS
BEGIN
RETURN CONVERT(DATETIME, RIGHT(#customDateString, 4) + RIGHT(LEFT(#customDateString, 4), 2) + LEFT(#customDateString, 2))
END
Change VARCHAR (dd-mm-yyyy) to date (yyyy-mm-dd) in SQL Server.
DECLARE #VarDate VARCHAR(10)
SET #VarDate = '22-02-1994'
SELECT CONVERT(DATETIME, CONVERT(VARCHAR, CONVERT(DATE, #VarDate, 103), 102))
You need to cast a string and not a int. Put some quotes:
convert(datetime, '23072009', 103)
And 103 gets the string like 'dd/mm/yyyy' and not 'ddmmyyyy'.

converting date from varchar to date

I am trying to change the date format of a column, the column is set as varchar column name date time. The problem is that i cannot actually change the data type because the data is automatically inputted by a PLC on the automation side. I need the date in a date or numeric value because when i run my queries i need to give the system a date range. I am trying to use substrings to work around this issue but am getting an error saying that the data type is out of range. here is the syntax of my query.
select cast(
(substring(datetime, 1, 4) + '-' +
SUBSTRING(DateTime, 5, 2) + '-' +
SUBSTRING(DateTime, 7, 2) + ' ' + '00:00:00.000') as dateTime) as "Date"
, ID1
, ID2
, diameter
, WeightTheoretical
, WeightActual
, StockType
from table1
where datetime is not null
and datetime <> ''
and datetime <> '0'
order by "Date", ID1;
Edit- the date format is as such 20120622:00:00:00:000
Assuming your date is with the format yyyymmdd, you can convert the varchar to datetime like this:
select convert(datetime, columname, 112)
It looks from your SQL that your date string is of the format YYYYMMDD
This should convert fine using either the CAST or CONVERT functions:
eg
SELECT CONVERT(datetime,'20120601')
SELECT CAST('20120601' as datetime)
both return the expected value as a datetime.
EDIT: Based on the supplied format you specified, I'd use the SubString to chop the supplied data down a bit:
eg
SELECT CONVERT(datetime,SUBSTRING('20120601',1,8))
Based on the format of your data in the table (20120622:00:00:00:000) you can do the following:
declare #date varchar(50)
set #date = '20120622:00:00:00:000'
select cast(left(#date, 8) as datetime)
or
select convert(datetime, left(#date, 8))
results:
2012-06-22 00:00:00.000