sql-server: Convert Char(14) to Datetime? - sql-server

With SQL-server 2008 database I have a char(14) data type that I want to convert to a datetime.
Example char(14) values:
20120209102026
20010131120000
The date format is yyyymmdd of some sort.
It seems like the values I posted are not the only format, because I get an "index out of range" error for some of the values. For this I can skip the ones that are not valid dates.

declare #c char(14)
select #c='20120209102026'
Select Cast(Substring(#c,1,8) + ' ' + Substring(#c,9,2)+':'+
Substring(#c,11,2)+':'+ Substring(#c,13,2) as DateTime)
Second Version that ignores out of range numeric values:
Select Cast(
Rtrim(Substring(#c,1,8)
+ Case When len(Substring(#c,9,4))>=4 then +' '+ Substring(#c,9,2) else '' end
+ Case When len(Substring(#c,11,2))=2 then +':'+ Substring(#c,11,2) else '' end
+ Case When len(Substring(#c,13,2))=2 then +':'+ Substring(#c,13,2) else '' end)
as Datetime)

This is ugly but if your format is yyyymmddhhmmss then you can use:
select cast(left(yourDate, 8)+' '+
SUBSTRING(yourDate, 9, 2)+':'+SUBSTRING(yourDate, 11, 2)+':'+RIGHT(yourDate, 2) as datetime)
from yourtable
See SQL Fiddle with Demo

A series of function calls but ends up with the same outcome.
Try like this:
select convert(datetime,STUFF(STUFF(STUFF(STUFF(STUFF('20010131120000',5,0,'/'),8,0,'/'),11,0,' '),14,0,':'),17,0,':'))
Look here for how STUFF works!

Related

SQL Server : How to validate for yyyymmddhhmmss

To avoid any conversion error, we'd like to validate if the target string can be converted to datetime using isdate formula, as follows.
CASE WHEN isdate(#targetstring)= 1 then cast(#targetstring as datetime) else '1900-01-01 00:00:00' end
It's working as expected, it returns 1 when it can be convertible.
select isdate('2021-06-22 23:27:00')
select isdate('20210622')
select isdate('20210622 23:00:00')
But yyyymmddhhmmss can't work as expected, it returns 0, even though the string can be converted to datetime.
select isdate('20210622230000')
If we use this, it seems to work.
select isdate(left('20210622230000', 8) + ' ' + substring('20210622230000', 9,2) + ':' + substring('20210622230000', 11,2) + ':' + substring('20210622230000', 13,2))
If there are any better idea, kindly let me know. Thank you.
Just saying you could trim down string manipulation using STUFF()
Example
Declare #S varchar(50)='20210622232715'
Select try_convert(datetime,stuff(stuff(stuff(#S,13,0,':'),11,0,':'),9,0,' '))
Results
2021-06-22 23:27:15.000

Convert multiple integer columns into a datetime value

I have the above table and I want to create a DATETIME value from it.
I've tried a number of ways using CONCAT, CONVERT and CAST to glue these together in a way that produces a datetime value and can't get there. I can produce a string that will convert like this.
CONCAT(
'''',
Year,
'-',
CASE LEN(Month) WHEN 1 THEN CONCAT('0', LTRIM(RTRIM(STR(Month)))) ELSE CAST(Month AS VARCHAR(2)) END,
'-',
CASE LEN(Day) WHEN 1 THEN CONCAT('0', LTRIM(RTRIM(STR(Day)))) ELSE CAST(Day AS VARCHAR(2)) END,
' ',
Hour,
':00:00.000',
''''
)
However, I wrap that output in a call to cast or convert it fails.
Can someone point me in the right direction?
Select Cast(Convert(nvarchar,[year])+'-'+Convert(nvarchar,[month])+'-'+Convert(nvarchar,[day])+' '+Convert(nvarchar,[hour])+':00:00.00' as datetime) from [YOUR TABLE]

How to create a new datetime from parts of dates and string in SQL Server?

How would I take the month, append "/01/" to it, then append the year to it, and finally append "00:01 AM" to it. I would like it end up looking like this:
2018/01/01 00:01 AM
I managed to do it in ACCESS but cannot accomplish this in SQL Server. Your help is greatly appreciated!
Using Concat,Cast,Year,Month and right
replace getdate() with your variable/field
select cast(concat(year(getdate()),right(concat('0',month(getdate())),2),'01',' 00:01 AM') as datetime)
or
select convert(varchar(22),cast(concat(year(getdate()),right(concat('0',month(getdate())),2),'01',' 00:01 AM') as datetime),100)
You can get the desired result with this script:
DECLARE #Date DATETIME;
SET #Date = '2018-01-02 13:45:30.000';
SELECT CAST(YEAR(#Date) AS CHAR(4)) + '/' + CASE WHEN MONTH(#Date) >= 10 THEN '' ELSE '0' END + CAST(MONTH(#Date) AS VARCHAR(2)) + '/01 00:01 AM';
Edit:
You can also create a function and make it reusable:
CREATE FUNCTION dbo.InitializeDate(#Date DATETIME)
RETURNS VARCHAR(19)
AS
BEGIN
RETURN CAST(YEAR(#Date) AS CHAR(4)) + '/' + CASE WHEN MONTH(#Date) > 10 THEN '' ELSE '0' END + CAST(MONTH(#Date) AS VARCHAR(2)) + '/01 00:01 AM';
END
GO
-- Usage example:
SELECT dbo.InitializeDate('2018-01-02 13:45:30.000') AS MyDate;
GO
-- Output:
2018/01/01 00:01 AM
There are different ways obviously - and always mention the version you are using since that affects the functionality that is available. I will say that it is highly unusual to require a time portion as you describe. I fear you have made an assumption and chosen a path that may turn into a problem. I suggest you read Tibor's discussion of the datetime datatype (and everything else as well). One possible way - which is really to demonstrate the functionality available in steps to get you thinking - is:
set nocount on;
declare #x datetime = '20180102 13:45:30.000';
with cte as (select cast('20180102 13:45:30.000' as datetime) as d1 union all
select '20180101 13:45:01:997' union all
select '20180228 00:00:05.003' union all
select '20120229 12:11:30.007')
select d1,
datefromparts(year(d1), month(d1), 1),
dateadd(second, 1, cast(datefromparts(year(d1), month(d1), 1) as datetime))
from cte;

SQL Server: Transfer YYYYMMDD-HHMMSS to mm/dd/yyyy hh:mm:ss

My SQL Server system is 2016.
As topic, I want to convert YYYYMMDD-HHMMSS to mm/dd/yyyy hh:mm:ss, and use dynamic SQL to fulfill this.
My data looks like this:
ID
20161119-075950
20161117-110952
20161118-153406
The datatype is nvarchar.
While I used the syntax below:
SELECT convert(date,convert(varchar(max),id,130), 130) from abc
An error Conversion failed when converting date and/or time from character string. shows up. I am thinking whether it is because SQL Server cannot identify this YYYYMMDD-HHMMSS as date type, and I need to convert this to YYYYMMDD hh:mm:ss first and then mm/dd/yyyy hh:mm:ss? Feel free to shed some lights. Thanks!
Select CONVERT(VARCHAR(25) , CAST(LEFT(ID , 8) AS DATETIME), 101)
+ ' ' + LEFT(RIGHT(ID , 6) ,2) + ':'
+ SUBSTRING(RIGHT(ID , 6) , 3,2) + ':'
+ RIGHT(ID , 2)
FROM TableName
Try it like this
DECLARE #tbl TABLE(ID NVARCHAR(100));
INSERT INTO #tbl VALUES
('20161119-075950')
,('20161117-110952')
,('20161118-153406');
--This is the actual select you need:
SELECT CAST(LEFT(ID,8) AS DATETIME) + STUFF(STUFF(RIGHT(ID,6),5,0,':'),3,0,':')
FROM #tbl
Your first part is strictly 8 chars long and implicitly casteable (unseperated datetime yyyymmdd). The time part is strictly 6 chars long. I use STUFF to insert the colons. This time can be added to a DATETIME. It will be - again implicitly - casted to DATETIME.
EDIT
To reach the given format you stated in the title just convert the first part first with code 101:
SELECT CONVERT(VARCHAR(10),CAST(LEFT(ID,8) AS DATETIME),101) + ' ' + STUFF(STUFF(RIGHT(ID,6),5,0,':'),3,0,':')
FROM #tbl
This should get the format you want... but there are probably better ways.
select
convert(varchar(16),convert(date,left(ID,8)),101) +
' ' +
substring(substring(ID,10,6),1,2) +
':' +
substring(substring(ID,10,6),3,2) +
':' + substring(substring(ID,10,6),5,2)

SQL Server datetime in 12AM/PM format without the millisecond

I would like to return my datetime data to the following format:
mm/dd/yy hh:mi:ssAM
According to the CONVERT documentation the closest thing that matches my spec is '131'
SELECT CONVERT(varchar, GETDATE(), 131)
but it doesn't exactly match my specifications.
EDIT:
I ended up doing the date formatting in my application layer which is PHP.
It was as simple as using the strtotime function to generate a UNIX timestamp and pass it into date funciton.
$date = date('m/d/Y g:ia', strtotime($row['date_time']));
Try this:
SELECT CONVERT(varchar, GETDATE(), 101) +
REPLACE(CONVERT(varchar, GETDATE(), 0),REPLACE(CONVERT(varchar, GETDATE(),107), ',',''),'')
This basically uses a method that's what you want for the DATE, then adds it to the time portion of what you want for the time only.
Although I feel that formatting should really be part of the UI, I guess if you really need it the below works - I'm sure there is an easier way to do this - but make this a UDF, and just use it in whatever query you want.
declare #date varchar(50)
set #date = (select CONVERT(varchar, GETDATE(), 131))
set #date = (select LEFT(#date,len(#date) - 6) + ' ' + RIGHT(#date,2))
set #date = right(#date,LEN(#date) - 11)
select CONVERT(varchar, GETDATE(), 101) + #date
You can assemble it from DATEPART()'s, and create a user defined function from it for easy re-use.
This is untested off the top of my head.. give it a shot:
CREATE FUNCTION fnSpecDate()
RETURNS VARCHAR(24)
AS
BEGIN
DECLARE #outData VARCHAR(24)
set #outData =
CONVERT(varchar,DATEPART(mm,GETDATE())) + "/"
+ CONVERT(varchar,DATEPART(dd,GETDATE())) + "/"
+ CONVERT(varchar,DATEPART(yy,GETDATE())) + " "
+ CASE WHEN DATEPART(hh,GETDATE()) > 12
THEN CONVERT(varchar,DATEPART(hh,GETDATE()) - 12)
WHEN DATEPART(hh,GETDATE()) = 0
THEN '12'
ELSE CONVERT(varchar,DATEPART(hh,GETDATE()))
END + ":"
+ CONVERT(varchar,DATEPART(mm,GETDATE())) + ":"
+ CONVERT(varchar,DATEPART(ss,GETDATE()))
+ CASE WHEN DATEPART(hh,GETDATE()) > 11
THEN "PM"
ELSE "AM"
END
RETURN #outData
END
Then in any regular query, you can just include dbo.fnSpecDate() as myDate

Resources