SQL date conversion year/datepart to datetime - sql

I am trying to convert from "tick" date format to a datetime format.
Example:
0000113326 to 2013-11-22 00:00:00.000
I know how to go the opposite way:
SELECT '00001' + RIGHT(CAST(YEAR(StartDate) AS varCHAR(4)), 2) + RIGHT('000' + CAST(Datepart(dy, StartDate) AS VARCHAR(3)), 3)
FROM table
I just need to reverse engineer it.
Any ideas?

Something like this?
DECLARE #tick varchar(20) = '0000113326'
SELECT dateadd(d, cast(right(#tick, 3) as int) - 1, '20' + substring(#tick, 6, 2) + '0101')

Related

Converting a FLOAT into DATE in SQL?

I wanted to know how to properly convert FLOAT value into a DATE?
The data we receive has a value oriented as such: YYYYMM ex. 201911 (today's Year + Month). However, all the values passing under the YYYYMM column signifies the first of the month ex. 201911 = 11/01/2019.
RIGHT([DATE],2) + '/01/' + LEFT([DATE],4) AS [DATE]
When I try converting it, it doesn't put it in a date format because I tried using it in a DATEADD function and it errored on the field I converted.
If your value is YYYYMM, then one simple method is to convert to a string and then a date:
select convert(date, convert(varchar(255), yyyymm) + '01')
Or, use datefromparts():
select datefromparts(floor(yyyymm / 100), yyyymm % 100, 1)
Please check this :
DECLARE #Date AS FLOAT;
SET #Date = 201911;
SELECT CONVERT(VARCHAR, CAST(CAST(LEFT(#Date,4) AS VARCHAR(4)) + '/01' + '/' + CAST(RIGHT(#Date,2) AS VARCHAR(2)) AS DATE) , 103) As CREATEDDATE
Will output 11/01/2019

How convert SQL Server DATE columns to DD:MM:YY and HH:MM:SS

I have a SQL Server column which is called DATE with this sample data 19452801102747.
I have this code
SELECT REPLACE(CONVERT(CHAR(10), [DATE], 103), '/', '')
I can get the date okay, is the final part of converting HH:MM:SS.
I am using SSMS 2018 and I would like to have two column separate; columns as shown on below image (DATE(DD:MM:YYYY))(TIME(HH:MM:SS))
Many thanks for your help.
We can use a simple substring to add date time separator in your varchar string,
because we cannot directly convert varchar to datetime..
DECLARE #date varchar(50) = '19452801102747' declare #date1 varchar(50)
SET
#date1 = SUBSTRING(#date, 1, 4) + '-' + substring(#date, 7, 2) + '-' + substring(#date, 5, 2) + ' ' + substring(#date, 9, 2) + ':' + substring(#date, 11, 2) + ':' + substring(#date, 13, 2)
SELECT convert(datetime, #date1)
First of all: You should not store datetime values in a non-appropriate datatype.
Your example looks like YYYYddMMHHmmss. There is no out of the box conversion for this...
The following will perform a number of string methods in order to transform your own format to a standard format. In this case I chose ISO8601, which is YYYY-MM-ddTHH:mm:ss:
DECLARE #YourDate VARCHAR(100)='19452801102747';
SELECT CONVERT(DATETIME,STUFF(LEFT(#YourDate,4) + STUFF(STUFF(STUFF(STUFF(SUBSTRING(#YourDate,7,1000),7,0,':'),5,0,':'),3,0,'T'),1,0,'-'),8,0,'-' + SUBSTRING(#YourDate,5,2)),126);
The STUFF() calls will insert some characters in the right position. Furthermore some string cutting will swap your ddMM to MMdd.

SQL Server : converting varchar field to date

I have in my table a varchar column with bunch of dates in the following format dd-MM-yyyy
31-12-2018
01-01-2019
02-01-2019
I need to write a date based query that gets all the dates before 01-01-2019.
I have tried using both CAST and CONVERT to convert these table values without luck.
Using CAST, my code is below:
SELECT
CAST('''' + SUBSTRING(arc_billed_to_date, 4, 2) + '-' + SUBSTRING(arc_billed_to_date, 1, 2) + SUBSTRING(arc_billed_to_date, 6, 5)+ '''' AS date),
CAST('''' + SUBSTRING(arc_billed_to_date, 7, 5) + '-' + SUBSTRING(arc_billed_to_date, 1, 2) + '-' + SUBSTRING(arc_billed_to_date, 4, 2) + '''' AS date),
CAST('''' + SUBSTRING(arc_billed_to_date, 7, 5) + '-' + SUBSTRING(arc_billed_to_date, 4, 2) + '-' + SUBSTRING(arc_billed_to_date, 1, 2) + '''' AS DATE),
CONVERT(DATE, '12-31-2018') AS x
FROM
wkpol
Using Convert
select Convert(datetime,'''' + SUBSTRING(arc_billed_to_date,7,5) + '-' + SUBSTRING(arc_billed_to_date,4,2) + '-' + SUBSTRING(arc_billed_to_date,1,2)+ '''',105) as x from wkpol
The error I get is
Conversion failed when converting date and/or time from character string.
Any help is appreciated.
SELECT *
FROM wkpol
WHERE convert(date, arc_billed_to_date, 103) < convert(date, '01/01/2019');
Well you are going to get many blames for using varchar field for date. Anyway, assuming it is a matter of another thread you can do the conversion like:
select * from myTable
where cast(right(arc_billed_to_date,4) +
substring(arc_billed_to_date,4,2) +
left(arc_billed_to_date,2) as date) < '20190101';
You wouldn't be using any index either.
In addition to Sean's comments, you can also set the DateFormat as DMY
Example
Declare #YourTable table (SomeCol varchar(50))
Insert Into #YourTable values
('31-12-2018')
,('01-01-2019')
,('02-01-2019')
Set DateFormat DMY
Select AsDate = try_convert(date,SomeCol)
From #YourTable
Returns
AsDate
2018-12-31
2019-01-01
2019-01-02

SQL Server Parse decimal to DateTime

I have a table in SQL Server 2017. In this table date stores as a decimal in next format:
20180717164540.2200000
YYYYMMDDhhmiss.nnnnnnn
4 digits for the year, 2 digits for a calendar month, 2 digits for a day of a month, 2 digits for a 24-hour based hour of the day in UTC, 2 digits for a minute of an hour, 2 digits for seconds of a minute, and fractional seconds.
My aim is to transform this format into DateTime and store it in another table in a database.
So my question is how to convert this format to DateTime format in SQL Server. As far as I know, you can not create custom date format like in Oracle.
I tried a lot of times with FORMAT AND CONVERT MSSQL functions but it not gonna work.
SELECT FORMAT(CONVERT(NVARCHAR(22), DECIMALCOLUMN), 'YYYYMMDDhhmiss') FROM SOURCE-TABLE;
Thank you for your help!
You were really close with your FORMAT idea. FORMAT gives you an NVARCHAR output, which you can explicitly CAST as a DATETIME2(7) (which maintains your precision level).
DECLARE #dateWannaBe DECIMAL(21,7) = 20180717164540.2200000;
SELECT CAST(FORMAT(#dateWannaBe,'####-##-## ##:##:##.#######', 'en-US') AS DATETIME2(7)) AS ActualDateTime2;
+-----------------------------+
| ActualDateTime2 |
+-----------------------------+
| 2018-07-17 16:45:40.2200000 |
+-----------------------------+
EDIT: Added the culture parameter to the FORMAT function per #JeroenMostert's comment.
a lot of stuffing
declare #dt decimal(30,8) = 20180717164540.2200000
select #dt, convert(datetime2,
stuff(
stuff(
stuff(
convert(varchar(30), #dt),
9, 0, ' '),
12, 0, ':'),
15, 0, ':')
)
/* RESULT
20180717164540.22000000 2018-07-17 16:45:40.2200000
*/
Try this:
DECLARE #date DECIMAL (30,7) =20180717164540.2200000
SELECT CONVERT(DATETIME, SUBSTRING(CONVERT(VARCHAR, #date),1,4) + '-' + SUBSTRING(CONVERT(VARCHAR, #date),5,2)
+ '-' + SUBSTRING(CONVERT(VARCHAR, #date),7,2) + ' ' + SUBSTRING(CONVERT(VARCHAR, #date),9,2) + ':' +
SUBSTRING(CONVERT(VARCHAR, #date),11,2) + ':' + SUBSTRING(CONVERT(VARCHAR, #date),13,2) + '.' + SUBSTRING(CONVERT(VARCHAR, #date),16,2))
You need SUBSTRING() function with stuff() :
select dateadd(ss, datediff(ss, 0, cast(stuff(stuff(substring(cast(#date as varchar(30)), 9, 20), 3, 0, ':'), 6, 0, ':') as datetime2)),
substring(cast(#date as varchar(10)), 1, 8)
)
. . .
DECLARE #TIME DECIMAL(38,8)
SET #TIME = '20180717164540.2200000'
SELECT CAST([DT] AS DATETIME) FROM(
SELECT LEFT(CAST(#TIME AS VARCHAR),4) +
SUBSTRING(CAST(#TIME AS VARCHAR),5,2) +
SUBSTRING(CAST(#TIME AS VARCHAR),7,2) + ' ' +
SUBSTRING(CAST(#TIME AS VARCHAR),9,2) + ':'+
SUBSTRING(CAST(#TIME AS VARCHAR),11,2) + ':' +
SUBSTRING(CAST(#TIME AS VARCHAR),13,2) AS DT
) AS X
Another approach, using LEFT, SUBSTRING and RIGHT
DECLARE #str nvarchar(22) = '20180717164540.2200000'
SELECT CONVERT(datetime2,
LEFT(#str,4)+
SUBSTRING(#str,5,2)+
SUBSTRING(#str,7,2)+' '+
SUBSTRING(#str,9,2)+':'+
SUBSTRING(#str,11,2)+':'+
SUBSTRING(#str,13,2)+'.'+
RIGHT(#str,7))
You could stuff and use DateTime2 instead of DateTime:
select
cast(stuff(stuff(stuff(
cast(mydate as varchar(30)),
13,0,':'),
11,0,':'),
9,0,' ') as datetime2) as myDateTime from myTable;

CAST Correct VARCHAR to DateTime

Good Day
I am working of a existing SQL Server Database. What the developers did is to keep the Date and time separate. The Date is in DateTime format (what I want) but the time is incorrect. if it is 14:30 it shows as 1430 when its 09:25 shows as 925. I am trying tyo combine the date and time to have a Date Time view for an program I am writing on top of this database.
I have created the date as a normal date like this:
CASE
WHEN LEN(T0.BeginTime) = 3 THEN '0' + LEFT(T0.BeginTime, 1) + ':' + RIGHT(T0.BeginTime, 2)
ELSE LEFT(T0.BeginTime, 2) + ':' + RIGHT(T0.BeginTime, 2)
END AS 'NEW Start Time'`
The date now looks like it's the correct format but when I want to combine the date and time I get VARCHAR to DateTime error.
How can I fix this?
This is the error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value (ONLY RAN 804 RECORDS)
Thanks
This should do the trick, Hope it helps.
DECLARE #DateTime TABLE (
DateWithTime DATE,
BeginTime INT);
INSERT INTO #DateTime
VALUES ('2014-08-04', '1525'),
('2014-08-04', '525'),
('2014-08-04', '15'),
('2014-08-04', '5'),
('2014-08-04', '0'),
('2014-08-04', '90')
;WITH cte_BeginTimeFix
AS (
SELECT
CONVERT(VARCHAR(10), DateWithTime, 120) AS DateWithTime,
RIGHT('0000' + CAST(BeginTime AS VARCHAR(4)), 4) AS BeginTime
FROM #DateTime
)
, cte_DateString
AS (
SELECT DateWithTime,
BeginTime,
DateWithTime + ' ' + STUFF(STUFF('00:00:00.000', 4, 2, RIGHT(BeginTime, 2)), 1, 2, LEFT(BeginTime, 2)) AS DateTimeStr
FROM cte_BeginTimeFix
)
SELECT DateWithTime,
BeginTime,
CASE
WHEN ISDATE(DateTimeStr) = 1 THEN CAST(DateTimeStr AS DATETIME)
ELSE NULL
END AS DateTimeStr
FROM cte_DateString
A different approach is to convert the time column in minutes and add it to the date
DATEADD(minute, T0.BeginTime / 100 * 60 + T0.BeginTime % 100
, CONVERT(VARCHAR, T0.BeginDate, 112))
with that the length of the time column doesn't matter
This should work:
CONVERT
(
DATETIME,
CONVERT(VARCHAR,T0.Date,112) +
' ' +
CASE
WHEN ISNULL(T0.BeginTime,'0') = '0'
THEN '00:00'
ELSE
RIGHT
(
'00' + LEFT(T0.BeginTime,LEN(T0.BeginTime) - 3),
2
) +
':' +
RIGHT(T0.BeginTime,2)
END
)