Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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


Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top