Convert seconds to datetime in SQL Server - sql

How to convert seconds to datetime? I try this, but results are not correct:
CONVERT(datetime, DATEADD(ms, dateTimeInSeconds, 0))
Here is an example: 1900-01-15 21:58:16.287 it's should be something like this 2010-11-02 14:56:50.997

Given your example, try this:
select DATEADD(s, dateTimeInMilliseconds, '19700101')

When you use the value zero for date, this is converted to 1900-01-01. Use the specific date that you have selected as epoch:
convert(datetime, dateadd(ms, dateTimeInMilliseconds, '2010-01-01'))
Note that the datetime data type doesn't have millisecond precision, the resolution is 1/300 second. If you for example have four milliseconds and convert it, you get 2010-01-01 00:00:00.003 rather than 2010-01-01 00:00:00.004. If you need to preserve the millisecond resolution, you need to use the datetime2 data type:
convert(datetime2, dateadd(ms, dateTimeInMilliseconds, cast('2010-01-01' as datetime2)))
Edit:
To use seconds instead of milliseconds, use s instead of ms in the dateadd call:
convert(datetime, dateadd(ms, dateTimeInSeconds, '1970-01-01'))

Informative time span string:
declare #seconds int = 93825
convert(varchar,(#seconds/86400)) + 'd:' + format(dateadd(ss,#seconds,0),'HH\h:mm\m:ss\s')
Result: 1d:02h:03m:45s

Related

Convert numeric column to time

I have a table of employee shifts which include shift start time and shift end time. The start time and end time columns are numeric with a full stop between hour and minute:
8.00
15.10
7.00
22.00
7.00
How can I convert these columns to time? I also need to calculate the difference between start time and end time in hours and minutes to work out the shift length.
In Sql Server use following code
declare #seconds numeric
set #seconds = 12366
select convert(char(8), dateadd(second, #seconds, ''), 114)
In Sql Server use following code
SELECT CONVERT(DATETIME, CONVERT(CHAR(9), CURRENT_TIMESTAMP, 112) + '22:00');
You can replace CURRENT_TIMESTAMP to your date
Ex:
SELECT CONVERT(DATETIME, CONVERT(CHAR(9), CONVERT(DATE,'2022-01-25'), 112) + '22:00');

Converting Unix time to DateTime 103

I have a stored procedure that joins two tables of hotel booking data, however, the API that I pull my data from uses Unix time. I need to convert this to DateTime to match with my companies fields.
Currently, my conversion looks like this.
IIF([start] IS NOT NULL,
CONVERT(varchar(10), [start], 103),'') as 'ArrivalDate'
This just returns the value 1547310796 so no conversion has been done.
How do I convert the value to match 103 Date Time?
This should do it:
SELECT DATEADD(second, 1547310796 - DATEDIFF(second, GETDATE(), GETUTCDATE()), '1970-01-01')
The DATEDIFF(second, GETDATE(), GETUTCDATE()) part will give you how far behind you are from UTC time. You need to subtract that many seconds from the UTC timestamp to get the local time.
I just wanted to come back to this and add another answer in that works if you just want the date and not time.
SELECT cast(DATEADD(S,[start], '1970-01-01') as date) as 'ArrivalDate'
works on Oracle/Sql
select TO_date ('19700101000000','YYYYMMDDHH24MISS') + NUMTODSINTERVAL(<YOUR_COLUMN>+ decode (sessiontimezone, '+01:00', 3600, '+02:00', 7200, 0) , 'SECOND') as ArrivalDate

SQL Server - Check if given date+time is between two datetime variables by exact date+time

I have two datetime columns in a DB table: #Start and #End.
Both columns contain the date and time, for example:
#Start: 2018-10-01 19:00:00
#End: 2018-10-10 23:59:00
I want to know if the current date is exactly between both datetimes considering the dates and the times.
So, 2018-10-08 16:37 and 2018-10-10 23:59:00 would match this range
and 2018-10-11 00:00:00 would not.
(In this case this date is one minute later than the End date, so it is not between my datetime range).
SELECT Id FROM Table1 WHERE GETDATE() BETWEEN Start AND End
I don't use GETDATE() in real code, I use an argument. The problem is that current date argument may contain seconds and milliseconds like 23:59:59.123. My code treats such date as not conforming given range. But I don't care about s/ms.
Is there a workaround?
Update:
The precision I want to achieve is in minutes. So I do not even need to take in account the seconds nor the milliseconds. The date time format I would be working on would be 'yyyy-MM-dd hh-mm' but I do not know how to use the BETWEEN clause converting the Start and End to the shown format so I can compare the dates.
You would seem to want this logic:
WHERE GETDATE() >= Start
AND GETDATE() < DATEADD(minute, 1, End)
Assuming that the time part of End is 23:59:00 it covers all possible values between 23:59:00 and 23:59:59.999...999.
SELECT Id FROM Table1 WHERE GETDATE() BETWEEN '2018-10-01 19:00:00' AND '2018-10-10 23:59:00'
TRY
SELECT Id FROM Table1 WHERE
CONVERT(varchar(16),GETDATE(),121) BETWEEN
CONVERT(varchar(16),[Start], 121)
AND
CONVERT(varchar(16),[END],121);
Example of rounding without strings
DECLARE #GetDateMinutes as datetime2;
DECLARE #X as datetime2 = getdate();
--round to minutes, could be made into a function
SET #GetDateMinutes = dateadd(minute,datepart(minute,#x),dateadd(hour, datepart(hour,#x),cast(CAST(#x as date) as datetime2)))
select #x, #GetDateMinutes
Truncate the seconds using the technique described here to avoid all string conversions, then just do your comparison. Here's a fully contained example that uses cross apply and values to encapsulate the truncation logic for start and end:
-- truncate minutes from current date time
declare #currentDateTime datetime2(0) = DateAdd(minute, DateDiff(minute, 0, Convert(datetime2(0), N'2018-10-01 23:58:32.912')), 0);
select #currentDateTime as CurrentDateTime
, a.*
from (values -- create a table of dummy values
(Convert(datetime2(3), N'2018-10-01 19:48:14.735'), Convert(datetime2(3), N'2018-10-10 02:00:00.000'))
, (Convert(datetime2(3), N'2018-10-01 22:43:19.532'), Convert(datetime2(3), N'2018-11-01 12:17:26.663'))
) as a (StartDateTime, EndDateTime)
cross apply (values(
-- truncate minutes from start date time
DateAdd(minute, DateDiff(minute, 0, Convert(datetime2(0), a.StartDateTime)), 0)
-- truncate minutes from end date time
, DateAdd(minute, DateDiff(minute, 0, Convert(datetime2(0), a.EndDateTime)), 0)
)) as b (StartDateTimeWithoutSeconds, EndDateTimeWithoutSeconds)
where #currentDateTime between b.StartDateTimeWithoutSeconds and b.EndDateTimeWithoutSeconds;
Your data appears to already have the s/ms truncated from start and end but figured I'd apply the same logic to all values involved just to be consistent. Here's the formula for stripping s/ms without all the "noise" from the example:
DateAdd(minute, DateDiff(minute, 0, Convert(datetime2(0), <SomeDateTime>)), 0)

Datetime entries turns into code

Hi I was generating a script so that my mssql datas would be in a sql format. After that I have a datetime column. An example entry is 2015-02-15 09:45:39.000
It turned into CAST(0x0000A44000A0DA84 AS DateTime)
How would I turn it into 2015-02-15 09:45:39 Removing the .000 and retaining the yyyy-mm-dd format?
You only want to remove the milliseconds?
convert it:
Select convert(varchar(50), getdate(), 120)
output = 2015-08-17 12:01:26
or set ms to 000:
Select DATEADD(ms, -DATEPART(ms, getdate()), getdate())
output = 2015-08-17 12:01:26.000

How to subtract Time Column from DateTime Column in SQL?

I have Crea_Date column which is a DateTime Column. I want to subtract the value in the IST column from crea_date Column and return a new column with the DateTime Value in it. My sample data is like this:
States crea_date IST
AB 2014-12-30 15:01:00.000 12:30:00.0000000
AK 2014-12-29 16:32:00.000 10:30:00.0000000
AZ 2014-12-18 16:07:00.000 11:30:00.0000000
Thanks in Advance
As strange as it might seem, you can add/subtract datetime values and it seems it's "normal" behavior.
Internally, datetime values are stored as the offset from 1/1/1900. If I add 22/1/2015 and 1/1/2015 I get 22/1/2130 because the second value is actually 115 years after 1900.
When you cast a time value to datetime only the time component is copied and the date component is set to 1/1/1900. In effect, you have an interval equal to your original time value.
This way I can subtract 10:30 hours from a specific datetime:
declare #d datetime='2014-11-04 12:51:00', #t time='10:30:00'
select #d -cast(#t as datetime)
//-----------------------
//2014-11-04 02:21:00.000
This behavior isn't an implementation quirk - it is explicitly permitted only for the datetime type. All other datetime types (eg datetime2, datetimeoffset) return the error Operand data type datetimeoffset is invalid for subtract operator.
If IST is an integer number of seconds:
SELECT DATEADD(s, -IST, crea_date)
FROM yourTable
If IST is of the TIME type:
SELECT DATEADD(ms, DATEDIFF(ms, IST, '00:00:00'), crea_date)
FROM yourTable
Try the below if IST is a character based column.
SELECT
Crea_Date, IST,
dateadd(hh,cast(substring(IST,1,2) as int),
dateadd(mi, cast(substring(IST, 4,2) as int),
dateadd(s, cast(substring(IST,7,2 ) as int), crea_date)
)) Final_Date
from [Yourtable]
You will get the added date in Final_Date column.
With slight modification in #0xF Answer I found the final Solution:
convert(varchar(10),
DATEADD(ms, DATEDIFF(ms, '00:00:00', IST), crea_date), 101) + right(convert(varchar(32
DATEADD(ms, DATEDIFF(ms, '00:00:00', IST), crea_date),100),8)