Difference between two dates in exact number of hours in SQL - sql

I would like to calculate the exact hours difference between two datetime variables. The hours difference should be exact like this:
1.5
2
6.25
Anybody please help out..Thanks in advance...

You could use DATEDIFF to find the difference in minutes and convert that into hours:
select datediff(mi, startdate, enddate)
Assuming 1.5 means 1 hour and 30 minutes you could simply divide the result by 60:
select datediff(mi, startdate, enddate) / 60.0

Keep it simple:
declare #date1 datetime
declare #date2 datetime
select #date1 = GETDATE();
select #date2 = '2013-02-02 14:05'
select DATEDIFF(hh, #date2, #date1)
Results
-----------
71
(1 row(s) affected)

it will help you....
Declare #Date1 dateTime
Declare #Date2 dateTime
Set #Date1 = '22:30:00'
Set #Date2 = '00:00:00'
Select Cast((#Date1 - #Date2) as Float) * 24.0

To get Exact Time Difference in HH:MM try the below code in MS-SQL
Declare #InTime datetime='2017-11-27 10:00:00',
#OutTime datetime='2017-11-27 11:15:00'
SELECT CONVERT(varchar(5),DATEADD(minute,DATEDIFF(minute,#InTime,#OutTime),0), 114)
-----------
Result
01:15

Please try:
declare #dt1 datetime, #dt2 datetime, #Seconds int
select #dt1='2013-02-05 14:05:55.113', #dt2 =getdate()
set #Seconds=datediff(second, #dt1, #dt2)
declare #Hour nvarchar(50)
declare #Min nvarchar(50)
declare #MinTemp int
if #Seconds >0
begin
set #Hour=cast((#Seconds / 3600) as nvarchar(20)) +' Hrs '
set #MinTemp= (#Seconds % 3600) / 60
set #Min=cast(#MinTemp as nvarchar(20))
if #MinTemp<10
select #Hour+'0'+#Min +' Min'
else
select #Hour+#Min +' Min'
end
else
select '00 Hrs 00 Min'

Related

How to get the number of hours between the two dates in sql

How to get the number of hours between the two dates in SQL Server
Example:
staffing_start_date (2017-08-01 06:00:00.00000)
staffing_end_dt (2017-08-01 18:00:00.00000)
You would use datediff():
select datediff(hour, staffing_start_date, staffing_end_date)
If you need the number of fractional hours, you can use below
DATEDIFF(second, staffing_start_date, staffing_end_date) / 3600.0
Please be aware of DateDiff's unexpected gotcha though. It does no rounding at all. It will truncate to the level you are looking for (Day, hour, min etc)
For example, both of these will return 1, so rounding Ferdinand's answer is a better fit most of the time.
declare #Start DateTime = '1/1/17 7:59 AM'
Declare #End Datetime = '1/1/17 8:00 AM'
select DATEDIFF(hour, #Start, #end)
declare #Start DateTime = '1/1/17 7:01 AM'
Declare #End Datetime = '1/1/17 8:59 AM'
select DATEDIFF(hour, #Start, #end)
Thanks #Jay Wheeler for your comments.
If you want hour to be very specific, you can use as given below:
Declare #Start DateTime = '1/1/17 7:59 AM'
Declare #End Datetime = '1/1/17 8:00 AM'
select DATEDIFF(MINUTE, #Start, #end) /60 AS Hour
Just in case you didn't understand the other answers, you can use DATEDIFF.
Dates are just numbers. The integral part of the number is the date and the fraction is the time. To get a difference in days, you can just cast to int and to get the difference in hours multiply by 24.
DECLARE #Date1 DateTime
DECLARE #Date2 DateTime
SELECT #Date1 = {ts '2017-08-29 00:00:00.000'},
#Date2 = {ts '2017-08-27 00:00:00.000'}
SELECT CONVERT(int, #Date1) - CONVERT(int, #Date2) AS DifferenceInDays
SELECT (CONVERT(int, #Date1) - CONVERT(int, #Date2)) * 24 AS DifferenceInHours
Or you could use DATEDIFF.
See DATEDIFF function - https://learn.microsoft.com/en-us/sql/t-sql/functions/datediff-transact-sql.
For your question, you can use:
DATEDIFF ( HOUR, staffing_start_date , staffing_end_dt )
DATEDIFF ( HH, staffing_start_date , staffing_end_dt )

How to add date and time in SQL Server

I have two variables #date of type datetime and #time of type time. I want to add both to get another datetime variable. And I want to perform further calculations on it.
Ex:
Declare #date datetime
Declare #time time
I want something like this
#date = #date + #time (but not concatenation)
SELECT #Startdate = DATEADD(DAY, -1, #date )
Is there any way?
You can tranform your time to seconds and add them to your datetime value:
DECLARE #datetime DATETIME = GETDATE(),
#time TIME = '01:16:24',
#timeinseconds INT
PRINT 'we add ' + CAST(#time AS VARCHAR(8)) + ' to ' + CONVERT(VARCHAR,#datetime,120)+ ':'
SELECT #timeinseconds = DATEPART(SECOND, #time)
+ DATEPART(MINUTE, #time) * 60
+ DATEPART(HOUR, #time) * 3600
SET #datetime = DATEADD(SECOND,#timeinseconds,#datetime)
PRINT 'The result is: ' + CONVERT(VARCHAR,#datetime,120)
Output:
we add 01:16:24 to 2015-07-17 09:58:45:
The result is: 2015-07-17 11:15:09
The only thing you are missing is that #time needs to be cast back to a datetime before adding to #date.
declare #date datetime = '2022-05-26'
declare #time time = '09:52:14'
declare #Startdate datetime
set #date = #date + convert(datetime,#time)
SELECT #Startdate = DATEADD(DAY, -1, #date)
Produces:
If you need to take only date part from #date and time part from #time - can convert your #date and #time to strings, concatenate the values and convert back to datetime:
select cast(convert(nvarchar(20), #date, 104) + ' ' +
convert(nvarchar(20), #time, 108) as datetime2)
Or, alternatively, if you need to add time to datetime value, you can do something like:
select dateadd(ms,
datepart(ms, #time),
dateadd(ss,
datepart(ss, #time),
dateadd(mi,
datepart(mi, #time),
dateadd(hh, datepart(hh, #time), #date))))
First of all convert #date and #time variables to NVARCHAR(), then concat them and after It convert It to DATETIME datatype. After It you can use DATEADD function on It. Try in following:
DECLARE #date DATETIME
DECLARE #time TIME
SET #date = GETDATE()
SET #time = '10:12:13'
SELECT DATEADD(DAY, -1, CAST(CONVERT(NVARCHAR(20), #date, 110) + ' ' +
CONVERT(NVARCHAR(20), #time, 108) AS DATETIME))
OUTPUT (Today day -1 + time '10:12:13'):
2015-07-16 10:12:13.000
I'm not sure what's going on here, but if your variables are datetime and time types, this should work just fine:
declare #date datetime
declare #time time
set #date = '20150717'
set #time = '12:34:56'
set #date = #date + #time
select #date, DATEADD(DAY,-1,#date)
See SQL Fiddle
If the problem is that #date contains also time part, you can use:
set #date = convert(datetime, convert(date, #date)) + #time
Your code is correct.
DECLARE #date DATETIME = '1/1/2020'
DECLARE #time TIME = '1:00 pm'
DECLARE #Startdate DATETIME
SET #date = #date + #time
SELECT #Startdate = DATEADD(DAY, -1, #date)
#date = 2020-01-01 13:00:00.000
#Startdate = 2019-12-31 13:00:00.000
It isn't concatenating, it is adding them together. The time on #date is 0:00:00.000, so it might appear to be concatenating them. But change #date to '1/1/2020 1:00 am' and then:
#date = 2020-01-01 14:00:00.000
#Startdate = 2019-12-31 14:00:00.000

SQL Separate hours in Start and EndDate

I'm need a help to create a Query. My problem is I have a StartDate and EndDate and need separate this in blocs of 60 minutes.
DECLARE #STARTDATE AS SMALLDATETIME
DECLARE #ENDDATE AS SMALLDATETIME
SET #STARTDATE = '2012-11-21 11:03:00'
SET #ENDDATE = '2012-11-21 13:04:00'
I need the return:
Hour, Time
11 , 57
12 , 60
13 , 04
You could use a recursive CTE. For example:
declare #startDate datetime = '2012-11-21 22:05:00'
declare #endDate datetime = '2012-11-22 01:06:00'
; with TimeList as
(
select #startDate as dt
union all
select dateadd(hour, 1, dateadd(hour, datediff(hour, 0, dt), 0))
from TimeList
where dateadd(hour, 1, dt) < #endDate
)
select dt
from TimeList
union all
select #endDate
The snippet dateadd(hour, datediff(hour, 0, dt), 0) removes the hours and minutes from a date. It does so by calculating the number of hours since date 0 and then adding that number of hours to date 0.
Live example at SQL Fiddle.
I unsure if i understood you but this will return the hour and minute after your start date at 60 min intervals.
DECLARE #STARTDATE AS SMALLDATETIME
DECLARE #ENDDATE AS SMALLDATETIME
DECLARE #time AS TABLE(id int identity(1,1), [hour] int, [time] int)
SET #STARTDATE = '2012-11-21 11:03:00'
SET #ENDDATE = '2012-11-21 13:04:00'
WHILE #STARTDATE < #ENDDATE
BEGIN
SELECT #STARTDATE = DATEADD(MINUTE,60,#STARTDATE)
INSERT INTO #time (hour,time)
VALUES(DATEPART(HOUR,#STARTDATE),DATEPART(MINUTE,#STARTDATE))
END
SELECT * FROM #time
You coan do it in three pieces. First piece is for the first hour, 60 minus the minute value, 2nd piece is time=60 for all hours between start+1 and end, third piece is end minutes
and then insert them into a temp table, as abstractChaos has done.
Insert into temp table like AbstractChaos:
DECLARE #STARTDATE AS SMALLDATETIME
DECLARE #ENDDATE AS SMALLDATETIME
DECLARE #TIME AS TABLE(id INT IDENTITY(1,1), [HOUR] INT, [TIME] INT)
SET #STARTDATE = '2012-11-21 11:03:00'
SET #ENDDATE = '2012-11-21 13:04:00'
INSERT INTO #TIME (HOUR,TIME)
VALUES (datepart(HOUR,#startdate) ,60 - datepart(MINUTE,#startdate) )
WHILE #STARTDATE < #ENDDATE
BEGIN
SELECT #STARTDATE = DATEADD(MINUTE,60,#STARTDATE)
INSERT INTO #TIME (HOUR,TIME)
VALUES(datepart(HOUR,#STARTDATE) , 60)
END
INSERT INTO #TIME (HOUR,TIME)
VALUES(datepart(HOUR,#enddate) , datepart(MINUTE,#startdate))

Time duration between two dates

i need to get the time duration in (hh:mm:ss) format between the two dates
2011/05/05 11:45:02 and 2011/05/01 08:09:57
For example if I had these two dates 2011/05/05 01:18:14 and 2011/05/05 11:00:00, the result would be: 02:18:14
DECLARE #dt1 datetime
DECLARE #dt2 datetime
SELECT #dt1 = '2011-05-05 11:45:02', #dt2 = '2011-05-05 08:09:57'
SELECT CONVERT(VARCHAR(8),#dt1-#dt2,108)
-- RESULT IS : 03:35:05
As far as i know there is no DATETIME_INTERVAL Data type in SQL (or TSQL) , so the only way you have to accomplish this is to manually format the result of a DATEDIFF function.
declare #hours as int
declare #minutes as int
declare #seconds as int
declare #time_interval as nvarchar(10)
set #hours = DATEDIFF(ss,'2011/05/05 01:18:14', '2011/05/05 11:00:00') / 3600
set #minutes = (DATEDIFF(ss,'2011/05/05 01:18:14', '2011/05/05 11:00:00') - #hours*3600)/60
set #seconds = DATEDIFF(ss,'2011/05/05 01:18:14', '2011/05/05 11:00:00') - #hours*3600 - #minutes * 60
set #time_interval = (cast(#hours as nvarchar) +':'+ cast(#minutes as nvarchar)+':'+ cast(#seconds as nvarchar))
print #time_interval
Try this:
declare #date1 datetime='2011/05/05 01:18:14', #date2 datetime='2011/05/05 11:00:00'
select CAST((#date2-#date1) as time(0))
Here is important order of elements in statement.In other case you will get 24h-your time.

Getting the Whole Time

How can I get the whole time like this datediff(time, logindate, logoutdate)
I know this built-in function doesn't accept time argument but how can I get the whole time rather than minute, millisecond, second etc. ?
logindate datetime2
logoutdate datetime2
I want something like 1:05:45 rather than portion of it.
Try this
create table dbo.UserLog (UserID VARCHAR(32),loginDate DATETIME,logoutDate DATETIME)
insert into userLog VALUES ('SPARKY','11/14/2009 3:25pm',getDate())
insert into userLog VALUES ('JANNA','11/14/2009 10:45am',getDate())
select UserId,loginDate,logoutDate,
convert(varchar(12),dateAdd(mi,datediff(mi,logindate,logoutdate),'Jan 1 1753 12:00AM'),114) as timeSpent
FROM userLog
Basically, adding the minutes difference between the dates to the earliest valid SQL date and returning the value formatted as a time.
To have difference in days:
select cast(logoutdate - logindate as float) from table_name
or just
select logoutdate - logindatefrom table_name
You can evaluate days, hours, minutes from it.
EDIT
To have it formatted as time:
SELECT CONVERT(VARCHAR,DATA_KOSZTU - DATA_OST_ZMIANY,108) FROM TR_KOSZT
It will work if users are not logged for more than 24 hours, because CONVERT is used to format datetime, not timespan.
Because MSSQL do not have timepsan datatype, datediff returning in absolute integer from milliseconds to years should be enough for you to create a instance of say TimeSpan in .NET.
What Sql Server version are you talking about? In SQL Server 2000 and later, at least,
SELECT datediff(ss,'2006-11-10 05:47:53.497','2006-11-10 05:48:10.420')
will give you the difference between those two datetimes in seconds.
E.g.
select CONVERT(varchar(10),GETDATE(),108)
Here's the solution you are looking for.
DECLARE #Date1 datetime
DECLARE #Date2 datetime
SET #Date2 = '2006-11-15 07:26:25.000'
SET #Date1 = '2009-11-15 05:35:45.000'
-- -----------------------
-- Math done by hand 1:50:40
--
DECLARE #TotalSeconds bigint
DECLARE #Hours bigint
DECLARE #Minutes bigint
DECLARE #Seconds bigint
DECLARE #HH varchar(20)
DECLARE #MM varchar(2)
DECLARE #SS varchar(2)
DECLARE #Result varchar(50)
--
SET #TotalSeconds = datediff(ss,#Date1 ,#Date2)
SET #Hours = FLOOR(#TotalSeconds / 3600)
SET #TotalSeconds = #TotalSeconds % 3600
SET #Minutes = FLOOR(#TotalSeconds / 60)
SET #Seconds = #TotalSeconds % 60
--
SET #HH = CAST(#Hours as varchar)
SET #MM = CAST(#Minutes as varchar)
SET #SS = CAST(#Seconds as varchar)
IF #Minutes < 10 SET #MM = '0' + #MM
IF #Seconds < 10 SET #SS = '0' + #SS
--
SET #Result = #HH + ':' + #MM + ':' + #SS
SELECT #Result