Convert Int data type to date - sql-server

The SQL server database I'm using has a field stored as an integer but it is a date. Currently it is showing 20191012. I've tried the below and it seems to convert it but I'd like to show it in 10/12/2019 format. Thanks.
CONVERT(DATE,CONVERT(VARCHAR(20),EFFDAT)) AS DATE_EFF

You first need to convert the number 20191012 to a date:
SELECT DATEFROMPARTS(
20191012 / 10000,
20191012 % 10000 / 100,
20191012 % 100
)
-- 2019-10-12 (DATE)
Then FORMAT it:
SELECT FORMAT(DATEFROMPARTS(
20191012 / 10000,
20191012 % 10000 / 100,
20191012 % 100
), 'MM/dd/yyyy')
-- 10/12/2019 (NVARCHAR)
The easier way is to convert the number to a string and do a couple of SUBSTRING()s.

DECLARE #myint int = 20191012
SELECT CAST(CAST(#myint as char(8)) as date) AS [theDate]
SELECT CONVERT(char(10), (CAST(CAST(#myint as char(10)) as date)), 101) AS [theDateStyleString]
Is one way, where the first query simply casts the data to the date datatype and the second query additionally converts to a string with the MM/DD/YYYY format. But understand that converting to a string is not the same as keeping the date datatype- since date functions and comparisons (>, <, etc) do not work correctly on strings.
This produces output:
theDate
----------
2019-10-12
theDateStyleString
------------
10/12/2019

Related

Convert Date to Integer in netezza

Please help in converting the date field to integer in YYYYMMDD format
Date col- YYYY-MM-DD HH:MM:SS - 2020-05-20 00:00:00
Required output - YYYYMMDD - 20200520
IN Aginity workbench (Netezza).
Reference: https://www.ibm.com/docs/en/psfa/7.2.1?topic=extensions-conversion-functions
Get the date as string
SYSTEM.ADMIN(ADMIN)=> select to_char(to_date('2021-01-01 10:11:12','YYYY-MM-DD HH:MI:SS'), 'YYYYMMDD') as str;
STR
----------
20210101
(1 row)
Now convert from string to integer base 10
SYSTEM.ADMIN(ADMIN)=> select string_to_int(to_char(to_date('2021-01-01 10:11:12','YYYY-MM-DD HH:MI:SS'), 'YYYYMMDD'), 10) as num;
NUM
----------
20210101
(1 row)
To verify it is indeed an integer let us add 5 to it
SYSTEM.ADMIN(ADMIN)=> select string_to_int(to_char(to_date('2021-01-01 10:11:12','YYYY-MM-DD HH:MI:SS'), 'YYYYMMDD'), 10) + 5 as numplus5;
NUMPLUS5
----------
20210106
(1 row)
Replace the date time string with your column in above examples.
to_char would be helpful here.
select string_to_int(
to_char(date_column, ‘YYYYMMDD’),
10 -- the base
)
...

How to convert a date with milliseconds into a date with just 000 instead of the milliseconds?

My incoming data contains a date in the following format:
2019-05-01 15:20:51.920
but after getting loaded into the target system it gets converted into the following :
2019-05-01 15:20:51.000
I would like to convert the source data and compare it with my target system since my target data is as per requirements.
ie 2019-05-01 15:20:51.920 should be converted to 2019-05-01 15:20:51.000
I am looking at convert functions as follows but it is only trimming the ms (using getdate(0 as a example):
select CONVERT(DATETIME2(3),getdate())
--2019-05-01 15:20:51.920
select CONVERT(DATETIME2(2),getdate())
--2019-05-01 15:20:51.92
Could someone tell me how I could achieve this? Thanks!
This should be also a more or less performant way:
SELECT GETDATE() AS OriginalValue
, CONVERT(DATETIME, CONVERT(VARCHAR(19), GETDATE(), 121)) ValueWithoutMilliseconds
The idea behind is to trim milliseconds, by cutting the last 4 characters of a fixed output format and then convert it back to a datetime
An output:
OriginalValue | ValueWithoutMilliseconds
----------------------------------------------------
2019-05-01 21:44:58.473 | 2019-05-01 21:44:58.000
Why not just cast the fractional seconds portion away using datetime2(0)?
declare #dateValue datetime2(3) = SysDateTime();
select Convert(datetime2(3), Convert(datetime2(0), #dateValue));
May be this should be give result what you are looking for,
DECLARE #TodayDatatime datetime
SET #TodayDatatime = DateAdd(DAY, DateDiff(DAY, 0, GetDate()), 0)
select GETDATE()
SELECT DateAdd(SECOND, DateDiff(SECOND, #TodayDatatime, GetDate()), #TodayDatatime)
Using the DATEADD/DATEDIFF method to truncate dates can work for this. Another option is to convert to datetime2(0).
SELECT DATEADD( SS, DATEDIFF(SS, '2020', aDate), '2020'),
CAST( aDate AS datetime2(0))
FROM (VALUES( CAST( '2019-05-01 15:20:51.920' AS datetime2(3))))x(aDate)
Note that the first option will truncate and the second one will round the value.

how to use sql to get number of seconds from a string formatted like "HH:MM:SS"

I have a C# program that recorded a TimeSpan value into a SQL Server table's varchar field. For example, the varchar field might have the value "00:12:05.7989790".
How could I use SQL code to get that total value in SECONDS? Since that varchar represents 12 minutes and 5 seconds, I would like a SQL statement that extracts it as "725".
I've tried some code like this:
select
Case when IsDate(the_value)=1 then datepart(HOUR, CONVERT(datetime, the_value))*360 else 0 end
+ Case when IsDate(the_value)=1 then datepart(MINUTE, CONVERT(datetime, the_value))*60 else 0 end
+ Case when IsDate(the_value)=1 then datepart(SECOND, CONVERT(datetime, the_value))*1 else 0 end
from mytable
but it complains "Conversion failed when converting date and/or time from character string."
Any suggestions would be greatly appreciated.
DATEDIFF function
https://msdn.microsoft.com/en-AU/library/ms189794.aspx
DATEDIFF(ss, '00:00:00.000', [your time column])
I would use datediff() and use explicit conversion to time:
select datediff(second, '00:00:00', convert(time, the_value))
If the units can exceed 23 hours, then you have a challenge, because the conversion will fail. In this case, string manipulation is an option:
select (left(the_value, 2) * 60 * 60 +
substring(the_value, 3, 2) * 60 +
substring(the_value, 5, 2)
) as seconds
This assumes that all strings are in the proper format. You can validate this with a case:
select (case when the_value like '[0-9]0-9]:[0-9[0-9]:[0-9][0-9]%'
then (left(the_value, 2) * 60 * 60 +
substring(the_value, 3, 2) * 60 +
substring(the_value, 5, 2)
)
end) as seconds

SQL Date-Time Conversion with nested converts experiences random conversion errors

Looking for assistance with a strange issue if anyone has ideas:
I have a SQL that statement works most of the time in a T-SQL script but crashes occasionally. I have identified the data that a crash occurs on and cannot identify any difference between data rows that work.
The goal of this code is to add the time to an already existing datetime value that has 00:00:00 as the time from the second time column (as outlined below). My goal is to combine both columns into YYYY-MM-DD HH:MM:SS format, but I had to convert them to char first to trim off the orignal 00:00:00.
Columns
LogDate - contains date only in DateTime format (YYYY-MM-DD HH:MM:SS)
LogTime - contains the time of the action and is in varchar format (HH:MM)
SQL Conversion
SELECT CONVERT(DATETIME, CONVERT(CHAR(8), LogDate, 112) + ' ' + CONVERT(CHAR(8), LogTime, 108))
FROM TestTable
WHERE EventSerial = '100001'
However, if I change the EventSerial in the above statement to a different row, such as '100002', the statement works.
The data for each row is below:
EventSerial 100001's values:
LogDate: 2015-04-02 00:00:00.000
LogTime: 10:04
EventSerial 100002's values:
LogDate: 2015-04-02 00:00:00.000
LogTime: 10:48
Running with data set 1 fails, running with data set 2 produces output. Also, running the code without the final datetime conversion works, or if I run the code with the string manually it works (as outlined below:)
SELECT CONVERT(CHAR(8), LogDate, 112) + ' ' + CONVERT(CHAR(8), LogTime, 108)
FROM TestTable
WHERE EventSerial = '100001'
SELECT CONVERT(DATETIME, '20150402 10:48')
SELECT CONVERT(DATETIME, '20150402 10:04')
Any suggestions, I'm sure its something silly that I'm missing (and I probably took the long way around the issue anyway. The desired output would be 2015-04-02 10:04:00
First, datetime has no format. (why?)
Second, you don't need to convert the datetime value to char to add hours and minutes, just use DateAdd:
SELECT DATEADD(Minute,
CAST(RIGHT(LogTime, 2) as int),
DATEADD(Hour,
CAST(LEFT(LogTime, 2) as int),
LogDate
)
)
FROM TestTable
WHERE EventSerial = '100001'
Also, note that convert does not hold a style for yyyymmdd hh:mm
Note: code was written directly here, there might be some mistakes.
I'm not sure why you're getting the error... possibly there are some unseen characters in your varchar time field... like a tab or something maybe? Try this query:
SELECT ascii(substring(LogTime,1,1)) Char1,
ascii(substring(LogTime,2,1)) Char2,
ascii(substring(LogTime,3,1)) Char3,
ascii(substring(LogTime,4,1)) Char4,
ascii(substring(LogTime,5,1)) Char5
FROM TestTable
WHERE EventSerial = '100001'
It should show these results:
Char1 Char2 Char3 Char4 Char5
----------- ----------- ----------- ----------- -----------
49 48 58 48 52
(1 row(s) affected)
This would be a bit more efficient:
select dateadd(minute, datediff(minute,0, LogTime), LogDate)
FROM TestTable
But this assumes that your date field always has 00:00:00 time information. If you want to be sure that is stripped out as well you could use:
select dateadd(minute, datediff(minute,0, LogTime), dateadd(day, datediff(day, 0, Logdate),0))
FROM TestTable

How to calculate difference in hours (decimal) between two dates in SQL Server?

I have to calculate the difference in hours (decimal type) between two dates in SQL Server 2008.
I couldn't find any useful technique to convert datetime to decimal with 'CONVERT' on MSDN.
Can anybody help me with that?
UPDATE:
To be clear, I need the fractional part as well (thus decimal type). So from 9:00 to 10:30 it should return me 1.5.
DATEDIFF(hour, start_date, end_date) will give you the number of hour boundaries crossed between start_date and end_date.
If you need the number of fractional hours, you can use DATEDIFF at a higher resolution and divide the result:
DATEDIFF(second, start_date, end_date) / 3600.0
The documentation for DATEDIFF is available on MSDN:
http://msdn.microsoft.com/en-us/library/ms189794%28SQL.105%29.aspx
Just subtract the two datetime values and multiply by 24:
Select Cast((#DateTime2 - #DateTime1) as Float) * 24.0
a test script might be:
Declare #Dt1 dateTime Set #Dt1 = '12 Jan 2009 11:34:12'
Declare #Dt2 dateTime Set #Dt2 = getdate()
Select Cast((#Dt2 - #Dt1) as Float) * 24.0
This works because all datetimes are stored internally as a pair of integers, the first integer is the number of days since 1 Jan 1900, and the second integer (representing the time) is the number of (1) ticks since Midnight. (For SmallDatetimes the time portion integer is the number of minutes since midnight). Any arithmetic done on the values uses the time portion as a fraction of a day. 6am = 0.25, noon = 0.5, etc... See MSDN link here for more details.
So Cast((#Dt2 - #Dt1) as Float) gives you total days between two datetimes. Multiply by 24 to convert to hours. If you need total minutes, Multiple by Minutes per day (24 * 60 = 1440) instead of 24...
NOTE 1: This is not the same as a dotNet or javaScript tick - this tick is about 3.33 milliseconds.
DATEDIFF but note it returns an integer so if you need fractions of hours use something like this:-
CAST(DATEDIFF(ss, startDate, endDate) AS decimal(precision, scale)) / 3600
Using Postgres I had issues with DATEDIFF, but had success with this:
DATE_PART('day',(delivery_time)::timestamp - (placed_time)::timestamp) * 24 +
DATE_PART('hour',(delivery_time)::timestamp - (placed_time)::timestamp) +
DATE_PART('minute',(delivery_time)::timestamp - (placed_time)::timestamp) / 60
which gave me an output like "14.3"
You are probably looking for the DATEDIFF function.
DATEDIFF ( datepart , startdate , enddate )
Where you code might look like this:
DATEDIFF ( hh , startdate , enddate )
DATEDIFF(minute,startdate,enddate)/60.0)
Or use this for 2 decimal places:
CAST(DATEDIFF(minute,startdate,enddate)/60.0 as decimal(18,2))
Declare #date1 datetime
Declare #date2 datetime
Set #date1 = '11/20/2009 11:00:00 AM'
Set #date2 = '11/20/2009 12:00:00 PM'
Select Cast(DateDiff(hh, #date1, #date2) as decimal(3,2)) as HoursApart
Result = 1.00
SELECT DATEDIFF(hh, firstDate, secondDate)
FROM tableName
WHERE ...

Resources