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

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

Related

SQL convert string(date or text) to date

I have a database which has a column called stringNextDue that contains data like dates (UK format) and text (e.g "overdue", "completed")
I am trying to create a view that shows courses that are due within a month from now:
WHERE
CONVERT(DATETIME, mt.stringNextDue , 103) < DATEADD(MONTH, 1, GETDATE())
This throws an error:
Conversion failed when converting date and/or time from character string.
Which is probably due to the fact that stringNextDue may contain actual strings of text.
I tried using
WHERE
ISDATE(mt.NextDateString) = 1
AND CONVERT(DATETIME, mt.stringNextDue , 103) < DATEADD(MONTH, 1, GETDATE())
But ISDATE only accepts US date formats therefore ignoring a lot of actual dates as strings
Tried set dateformat 'dmy', which fixed the IsDate issue, but it cannot be used in views.
Any suggestions?
Server update is not an option
If you cannot use the new TRY_CONVERT you might use a function like this:
Attention: This will not catch a wrong date like 31.06.2016, you'd have to modify the BETWEEN 1 AND 31 if you need this...
Attention2: If your text might include characters forbidden in xml you should replace < with <, > with > and & with & ...
CREATE FUNCTION dbo.TestDate(#TestString VARCHAR(100))
RETURNS DATE
AS
BEGIN
DECLARE #x XML=CAST('<x>' + REPLACE(#TestString,'.','</x><x>') + '</x>' AS XML)
DECLARE #p1 VARCHAR(10) = #x.value('x[1]','varchar(10)');
DECLARE #p2 VARCHAR(10) = #x.value('x[2]','varchar(10)');
DECLARE #p3 VARCHAR(10) = #x.value('x[3]','varchar(10)');
IF LEN(#p1)=2 AND ISNUMERIC(#p1)=1 AND CAST(#p1 AS INT) BETWEEN 1 AND 31
AND LEN(#p2)=2 AND ISNUMERIC(#p2)=1 AND CAST(#p2 AS INT) BETWEEN 1 AND 12
AND LEN(#p3)=4 AND ISNUMERIC(#p3)=1 AND CAST(#p3 AS INT) BETWEEN 1900 AND 2100
RETURN CONVERT(DATETIME, #TestString , 103);
RETURN NULL;
END
GO
SELECT
dbo.TestDate('overdue') AS SureNoDate
,dbo.TestDate('01.04.2016') AS EuropeanDate
,dbo.TestDate('2016.04.01') AS WrongFormat
,dbo.TestDate('01.13.2016') AS BadDate;
GO
DROP FUNCTION dbo.TestDate;
The result
SureNoDate EuropeanDate WrongFormat BadDate
NULL 2016-04-01 NULL NULL
You might pass back a valid date (RETURN GETDATE() ?) instead of RETURN NULL for your comparisson outside. This depends on your needs...
It should be possible to replace WHERE clause using this:
SELECT *
FROM
-- sample data
(values('2015-01-01'),('01-01-2015'), ('x-x-x-x')) mt(NextDateString)
-- Replace WHERE statement with the following
CROSS APPLY
(
SELECT
RIGHT('0000'+PARSENAME(REPLACE(mt.NextDateString, '-', '.'), 1),4) yyy,
RIGHT('0000'+PARSENAME(REPLACE(mt.NextDateString, '-', '.'), 2),4) mmm,
RIGHT('0000'+PARSENAME(REPLACE(mt.NextDateString, '-', '.'), 3),4) ddd
) x
WHERE
x.yyy BETWEEN '1950' AND '2050'
AND x.mmm BETWEEN '0001' AND '0012'
AND x.ddd BETWEEN '0001' AND '0031'
AND ISDATE(mt.NextDateString) = 1
AND x.yyy+x.mmm+x.ddd < CONVERT(char(8), DATEADD(MONTH, 1, GETDATE()), 112)
Result:
NextDateString yyy mmm ddd
01-01-2015 2015 0001 0001
Thank you for suggestions,
I fixed it by setting language to British on user settings
EXEC sp_defaultlanguage 'username', 'british'

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

SQL Server - Converting date in "20140410" format to 04/10/2014 format

I have a table in a server that outputs the date in the following format YEARMONTHDAY
Example 20140410.
Question is how to I convert it to be as MONTH/DAY/YEAR, example 04/10/2014
Thanks!
David
Try this:
declare #theDate varchar(8)
set #theDate = '20140410'
select convert(varchar(10),cast(#theDate as date),101)
I think you can use:
SELECT convert(varchar, getdate(), 101);
Here is one way to do it:
declare #dt CHAR(8) = '20140131'
select #dt, CONVERT(DATE,#dt) as newDt
Here is a link on the CONVERT function http://msdn.microsoft.com/en-us/library/ms187928.aspx and one on date types http://msdn.microsoft.com/en-us/library/bb630352.aspx
Here are 2 different versions, one version for if all values are valid YYYYMMDD format, and one that will still work with invalid dates (but will return null for invalids).
DECLARE #tblTest TABLE (id int not null identity, myDate int not null)
INSERT INTO #tblTest(myDate)
VALUES(20140308),(20140410)
;
--QUERY 1: if all values in your table are valid dates, then you can use this
SELECT t.id, t.myDate
, myDateFormatted = CONVERT(varchar(10),CONVERT(DATE, CONVERT(VARCHAR(10),t.myDate)),101)
FROM #tblTest t
--NOW INSERT SOME INVALID DATES AS WELL
INSERT INTO #tblTest(myDate)
VALUES(20140132),(48)
;
--NOW IF THERE ARE INVALID DATE, THEN USING QUERY 1 WOULD CAUSE AN ERROR: Conversion failed when converting date and/or time from character string
--QUERY 2: if there are ANY invalid values in your table, then you can use this
SELECT t.id, t.myDate
, myDateFormatted =
CASE
WHEN ISDATE(t.mydate) = 1 and len(t.myDate) = 8
THEN CONVERT(varchar(10),CONVERT(DATE, CONVERT(VARCHAR(10),t.myDate)),101)
ELSE NULL --THIS IS AN INVALID DATE
END
FROM #tblTest t
;

combine 2 varchar column's data and convert to datetime

I have 2 columns in a table of varchar datatype.
date and type are the column names in table.
the data present in the table looks like this
date time
20090610 132713
20090610 132734
i need ms sql server query to concatenate these 2 columns data and display as datetime format.
Note :
1. the datatype of those 2 columns cannot be changed now.
2. i tried
select convert(datetime,date + time)
it says "Conversion failed when converting date and/or time from character string."
Suggest the possible solution.
This will return a datetime. The bottom line is to be replaced by your table
select convert(datetime,date,112)+
coalesce(stuff(stuff(rtrim(time), 5,0,':'), 3,0,':'), '') newdate
from
(VALUES ('20090610','132713'),('20090610', '132734'),('20090610', ' ')) yourtable(date,time)
Result:
newdate
2009-06-10 13:27:13.000
2009-06-10 13:27:34.000
2009-06-10 00:00:00.000
You can get it using
SELECT
convert(varchar, convert(datetime, date), 111)
+ ' ' + substring(time, 1, 2)
+ ':' + substring(time, 3, 2)
+ ':' + substring(time, 5, 2)
CREATE TABLE #Table
(
[date] VARCHAR(100),
[time] VARCHAR(100)
)
INSERT INTO #Table VALUES
('20090610','132713'),
('20090610','132734')
;WITH Bits_CTE
AS
(
SELECT
[Date],
[Time],
[hrs] = CONVERT(INT,SUBSTRING([Time], 1, 2)),
[mns] = CONVERT(INT,SUBSTRING([Time], 3, 2)),
[secs] = CONVERT(INT,SUBSTRING([Time], 5, 2))
FROM #Table
)
SELECT
[Date],
[Time],
DATEADD(HOUR,[hrs],
DATEADD(MINUTE,[mns],
DATEADD(SECOND,[secs],[Date])))
FROM Bits_CTE
CREATE FUNCTION [dbo].[DateTimeAdd]
(
#datepart date,
#timepart time
)
RETURNS datetime2
AS
BEGIN
RETURN DATEADD(dd, DATEDIFF(dd, 0, #datepart), CAST(#timepart AS datetime2));
END
Sorry - Missed the bit in your question about storing the date and time as varchars. You would therefore still need to convert these data itemsbefore using this function.

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