How do I add Time in SQL? - sql

So my data is 1:30 PM. I want to have a Data when user selects a time, I want it to add 1hr 30mins to that and make the data as 1:30 PM - 3:00 PM. I've been searching for an answer and tried some workarounds but i couldn't get it. BTW the datatype of my Time is Varchar, because when I tried using the Time datatype I had some issues on inserting from C# to SQL

tested with sql-server 2008
declare #t varchar(25)
set #t = '1:30 PM'
--conert a varchar to time
select CONVERT(time, #t)
--if you want to add 90 minutes to it
select DATEADD(minute,90,CONVERT(time, #t))

--this does a few things
-- 1) converts the time stored as a varchar to the time datatype
-- 2) adds 90 minutes
-- 3) converts the time result back to the varchar datatype
select convert(varchar(10), dateadd(mi, 90, convert(time, '1:30 PM')), 100)
--this will show a final result of "3:00PM"
EDIT:
The following query will also return a varchar with the space between before the AM/PM.
select format(dateadd(mi, 90, convert(datetime, '1:30 PM')), 'h:mm tt')
The 'h:mm tt' is written with one "h" so that it will show up as "3:00 PM", instead of "03:00 PM".
Using Replace:
This would be how I would use replace to get to the goal of "3:00 PM"
select replace(replace(convert(varchar(10), dateadd(mi, 90, convert(time, '1:30 PM')), 100), 'P', ' P'), 'A', ' A')

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)

SQL: Add space before AM/PM after military time conversion

I researched everywhere about this but I cannot seem to find it.
I have a column called OPEN_TIME which contains military time such as:
1900-01-01 23:00:00.000
I only want to extract the time, which I did successfully by doing:
LTRIM(RIGHT(CONVERT(varchar, OPEN_TIME, 100), 7))
However, this gives me a time of:
11:00PM
I would like to put a space before AM/PM so that it looks like:
11:00 PM
Not sure if this is as simple as it looks? Any advice would be appreciated.
If 2012+ you can use Format()
Declare #Open_Time DateTime = '1900-01-01 23:00:00.000'
Select Format(#Open_Time,'hh:mm tt')
Returns
11:00 PM
I should note that Format() is not known for its performance.
In any version of SQL Server you can use the REPLACE function
REPLACE(LTRIM(RIGHT(CONVERT(varchar, OPEN_TIME, 100), 7)),'PM',' PM')
If you aren't using 2012 or don't want to use Format you can accomplish this with STUFF.
Declare #Open_Time DateTime = '1900-01-01 23:00:00.000'
SELECT
STUFF(
LTRIM(RIGHT(CONVERT(VARCHAR, #OPEN_TIME, 100), 7)),
LEN(LTRIM(RIGHT(CONVERT(VARCHAR, #OPEN_TIME, 100), 7))) - 1,
0,
' ')
https://msdn.microsoft.com/en-us/library/ms188043.aspx

How to assign current date with specific time to column?

How do i assign current date with a specific time?
let's say 8:00:00 AM to Column EXIT_DT of datatype datetime??
I have tried GETDATE() AS EXIT_DT but it gives me current datetime. I am using Sql server 2005. Any help?
Lets say Today is 1/3/2013 and i want my result to return as a datetime datatype with value 1/3/2013 8:00:00 AM. If i run the statement ytd, the result will be 1/2/2013 8:00:00 AM
This formula will always produce 08:00 for the day it is called, and avoids string manipulation:
select DATEADD(day,DATEDIFF(day,'20010101',GETDATE()),'2001-01-01T08:00:00')
Try to avoid solutions that convert to and from strings - treating datetime values as strings is one of the largest sources of bugs.
It works by computing the number of days (as an integer) that have elapsed since 1st January 2001. It then adds that same number of days to 08:00 on 1st January 2001.
You can try this :
DECLARE #dt datetime;
SET #dt=CONVERT(DateTime, CONVERT(VARCHAR,GETDATE(),101)+' 8:00:00')
SELECT CONVERT(VARCHAR, #dt, 101)+' '+ LTRIM(RIGHT(CONVERT(VARCHAR(20),#dt, 100), 7))
Visit http://www.sql-server-helper.com/tips/date-formats.aspx for datetime formats.
Use Convert along with getdate() to get specific formats.
ex:
SELECT CONVERT(VARCHAR(30),GETDATE(),113)
This is a bit stupid, but it works
select cast(cast(getdate() as date) as datetime) + '08:00:00'
it casts the getdate() to date thus losing the hours, than it casts it to datetime and adds 8 hours.
If you want to avoid implicit conversion of varchar to datetime, you could use this version:
select cast(cast(getdate() as date) as datetime)
+ convert(datetime,'08:00:00',114)
This is also working. (1). convert today's date to ISO format (yyyymmdd) (2). add the time, (3). convert back to datetime
Select convert(datetime, convert(varchar, getdate(),112) + ' ' + '8:00:00AM')
--Results
2013-01-03 08:00:00.000
If you need in specific format you need to convert back to varchar again.
-- AM/PM --
SELECT TO_CHAR(sysdate, 'MM/DD/YYYY HH:MI:SS AM') FROM dual
/
-- 24 hrs format --
SELECT TO_CHAR(sysdate, 'MM/DD/YYYY HH24:MI:SS') FROM dual
/