Time duration between two dates - sql-server-2005

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.

Related

Data operations

I wrote a stored procedure who take a reference date, and add a hour to this element.
Here is my line doing the operation :
DATEADD(day, DATEDIFF(DAY, 0, #conductor_date), [HOUR])
For example, whith #conductor_date = '2015-10-15' and [HOUR] = 23:00 it works and generate me a date like that : '2015-10-15:23:00:00'
I face a logical issue when the value [HOUR] is more than 24. In fact, to solve my problem I need to generate '2015-10-16:00:40:00' when [HOUR] = 24:40
Actualy with this values, I face the logical following exception :
The conversion of a varchar data type to a datetime data type resulted
in an out-of-range value.
To sum up, I need to take care of hours that are more than '23:59' and switch to the next day :
DECLARE #conductor_date datetime
DECLARE #hour varchar(5)
SET #conductor_date = '2015-10-15'
SET #hour = '24:40'
SELECT DATEADD(day, DATEDIFF(DAY, 0, #conductor_date), #hour)
Expected : 2015-10-16:00:40:00
According to the documentation, date / time types don't support times larger then 23:59:59.9999999. You have to do manual string parsing for this.
First you need to extract the total hours, divide that by 24 to get total days. Then calculate leftover hours, and with that reconstruct your time offset.
With these in hand, you can build your required output value:
DECLARE #v VARCHAR(20) = '24:40'
DECLARE #start VARCHAR(20) = '2015-10-15'
DECLARE #days INT
DECLARE #leftover INT
SET #leftover = CAST(LEFT(#v, 2) AS INT)
SET #days = #leftover / 24
SET #leftover = #leftover - #days * 24
SET #v = CAST(#leftover AS VARCHAR(2)) + SUBSTRING(#v, 3, 20)
SELECT DATEADD(DAY, #days + DATEDIFF(DAY, 0, #start), #v)
Here's a working SQLFiddle.
This supports time string that start with HH (leading zeros) with any valid accuracy (HH:mm:ss.fffffff).
You can split your #hour field into hours and minutes and add them separately:
DECLARE #conductor_date datetime
DECLARE #hour varchar(5)
DECLARE #hours int
DECLARE #minutes int
DECLARE #offset datetime
SET #conductor_date = '2015-10-15'
SET #hour = '24:40'
SET #hours = cast(left(#hour, 2) as int)
SET #minutes = cast(right(#hour, 2) as int)
SET #offset = dateadd(day, datediff(day, 0,#conductor_date), 0) -- the begin of the day
SELECT DATEADD(hour, #hours, dateadd(minute, #minutes, #offset))
Of course all can be done in one line but for sake of visualization I have put it into separate statements.
You may try below query
SELECT DATEADD(MINUTE,(LEFT(#hour,2)*60+RIGHT(#hour,2)),#conductor_date)

How to create Time with Hour+Minute+Seconds in sql server 2008

I have three var char values as
#hour = '18'
#minute = '25'
#seconds = '45'
I need output in the form of '18:25:45'
Select from Convert(Time,#hour+#minute+#seconds)
values in hour minute and seconds coming from SSRS report drop down
You can 'add-up' the values from zero, like this:
declare #hour smallint = 18
declare #minute smallint = 25
declare #seconds smallint = 45
declare #result time
SELECT #result = DATEADD(hour, #hour, DATEADD(minute, #minute, DATEADD(second, #seconds, 0)))
An implicit conversion is not allowed. One solution could be to organise the format as a string and then convert to time as below.
declare #hour smallint = '18'
declare #minute smallint = '25'
declare #seconds smallint = '45'
declare #format varchar(8) = (select (CAST(#hour as varchar(2)) + ':'+ CAST(#minute as varchar(2))+':'+ CAST(#seconds as varchar(2))))
select CAST(#format as time)
Try with this 24-H date format, It will Work.
SELECT CONVERT(VARCHAR(8),GETDATE(),108) AS TimeResult

Getting Datetime by Year, Month, Date

I want to get date by Using Year, Month and Day functions. Example
declare #Date smalldatetime
select #Date = Year('20140530') + Month('20140530') + Day('20140530')
What I want is to assign #Date = '20140530' as smalldatetime. But I want to do this by means of somwething similar to above expression. How can Ido this. Thanks in advance.
Instead try something like below
declare #Date varchar(20)
select #Date = cast(Year('20140530') as varchar) +
cast(Month('20140530') as varchar) +
cast(Day('20140530') as varchar)
select #Date
results in: 2014530.
(OR) like below
declare #Date VARCHAR(20)
select #Date = cast(Year('20140530') as varchar) + '-' +
cast(Month('20140530') as varchar) + '-' +
cast(Day('20140530') as varchar)
select cast(#Date as smalldatetime)
results in: 2014-05-30 00:00:00
Year()/Month()/DaY() functions returns the year/Month/Day as Integer. What you are actually doing can be simulated as below
declare #Date smalldatetime
set #Date = 2049
select #Date
which will result in : 1905-08-12 00:00:00
Use Like, Set will give the Date in #Date instead of select
declare #Date smalldatetime
set #Date = Year('20140530') + Month('20140530') + Day('20140530')
print #Date

Difference between two dates in exact number of hours in 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'

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