views:

85

answers:

6

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.

+1  A: 

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.

LukLed
A: 

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.

o.k.w
A: 

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.

Alex Martelli
SQL Server, but I want something like 1:05:45 rather than portion of it.
Braveyard
I mean SQL Server 2008
Braveyard
+4  A: 

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.

Sparky
A: 

E.g. select CONVERT(varchar(10),GETDATE(),108)

priyanka.sarkar
A: 

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


Cape Cod Gunny