Time difference with hours, minutes and seconds in SQL Server - sql-server

I need to find time difference between two columns with hours, minutes and seconds.
These are two datetime columns in my table:
STOP_TIME Start_Time
------------------------------------------------------
2016-05-10 03:31:00.000 2016-05-10 02:25:34.000
I calculated second difference for stoptime and starttime. 3926 is the second difference.
I need to convert this to time format hh:mm:ss.

This should work for you -
DECLARE #STOP_TIME DATETIME = '2016-05-10 03:31:00.000',
#Start_Time DATETIME = '2016-05-10 02:25:34.000'
SELECT
RIGHT('0' + CAST(DATEDIFF(S, #Start_Time, #STOP_TIME) / 3600 AS VARCHAR(2)),2) + ':'
+ RIGHT('0' + CAST(DATEDIFF(S, #Start_Time, #STOP_TIME) % 3600/60 AS VARCHAR(2)),2) + ':'
+ RIGHT('0' + CAST(DATEDIFF(S, #Start_Time, #STOP_TIME) % 60 AS VARCHAR(2)),2)

Sql server supports adding and subtracting on Datetime data type, so you can simply do something like this:
DECLARE #StartTime datetime = '2016-05-10 02:25:34.000',
#EndTime datetime = '2016-05-10 03:31:00.000'
SELECT CAST(#EndTime - #StartTime as Time) As TimeDifference
Result: 01:05:26
Note: As TT rightfully wrote in his comment, casting to time will only work if the difference between #EndTime and #StartTime is less then 24 hours.
If you need to compare times that are further apart, you need to use one of the other solutions suggested.

Related

Find duration in hh:mm:ss in SQL Server

I have starttime and endtime columns in my table and I want to get time difference between the two. But however I want the difference in hh:mm:ss format which I am not getting.
Declare #starttime = '7/23/2020 3:30:02 PM'
Declare #endtime = '7/23/2020 3:30:07 PM'
Select cast(#starttime - #endtime as Time) As Timedifference
I get 00:00:05.000000 which I don't want.
This may help you:
select convert(varchar(5),DateDiff(s, #startDate, #EndDate)/3600)+':'
+convert(varchar(5),DateDiff(s, #startDate, #EndDate)%3600/60)+':'
+convert(varchar(5),(DateDiff(s, #startDate, #EndDate)%60)) as [hh:mm:ss]
From SQL Server 2012 you can use FORMAT function.
In the following post you can find many solutions of this:
SQL time difference between two dates result in hh:mm:ss
Below the best solution if you have SQL Server 2012 or later version:
--get the difference between two datetimes in the format: 'hh:mm:ss'
CREATE FUNCTION getDateDiff(#startDate DATETIME, #endDate DATETIME)
RETURNS VARCHAR(10)
AS BEGIN
DECLARE #seconds INT = DATEDIFF(s, #startDate, #endDate)
DECLARE #difference VARCHAR(10) =
FORMAT(#seconds / 3600, '00') + ':' +
FORMAT(#seconds % 3600 / 60, '00') + ':' +
FORMAT(#seconds % 60, '00')
RETURN #difference
END
For FORMAT documentation look here

How to calculate time difference in T-SQL

I have created a table with columns of datatype time(7)
I want to calculate the time difference between them.
Table time:
id timefrom timeto result
--------------------------------------
1 13:50:00 14:10:00 00:20:00
2 11:10:00 11:00:00 23:50:00
For example:
Time From 13:50
Time To 14:10
Result should show 00:20.
Is there a function for this?
DATEDIFF(hour, UseTimeFrom, UseTimeTo) hourtime,
(DATEDIFF(MINUTE, UseTimeFrom , UseTimeTo)) - (((DATEDIFF(hour, UseTimeFrom, UseTimeTo)) * 60)) as mintime
You can do it this way:
select *, convert(time, convert(datetime, timeto) - convert(datetime, timefrom))
from table1
This will convert the times to datetime for day 0 (1.1.1900) and then do the calculation and in case the timeto is smaller it will get to previous day, but convert to time will get the time part from it.
Example in SQL Fiddle
There's no built-in function - but you could relatively easily write your own T-SQL stored function to calculate this - something like this:
CREATE FUNCTION dbo.TimeDifference (#FromTime TIME(7), #ToTime TIME(7))
RETURNS VARCHAR(10)
AS BEGIN
DECLARE #Diff INT = DATEDIFF(SECOND, #FromTime, #ToTime)
DECLARE #DiffHours INT = #Diff / 3600;
DECLARE #DiffMinutes INT = (#Diff % 3600) / 60;
DECLARE #DiffSeconds INT = ((#Diff % 3600) % 60);
DECLARE #ResultString VARCHAR(10)
SET #ResultString = RIGHT('00' + CAST(#DiffHours AS VARCHAR(2)), 2) + ':' +
RIGHT('00' + CAST(#DiffMinutes AS VARCHAR(2)), 2) + ':' +
RIGHT('00' + CAST(#DiffSeconds AS VARCHAR(2)), 2)
RETURN #ResultString
END
This function uses the integer division (/) and integer remainder (%) operators to calculate the number of hours, minutes and seconds that those two times are apart, and then concatenates those together into a string as you are looking for.
SELECT
dbo.TimeDifference('13:50:00', '14:10:00'),
dbo.TimeDifference('13:50:00', '15:51:05'),
dbo.TimeDifference('13:50:00', '15:35:45')
Sample output:
00:20:00 02:01:05 01:45:45

Convert hh:mm:ss to hh:mm in SQL Server

I have time as 04:02:00, I want it only as 4:02 using SQL Server
I have tried this code:
#time time
set #time ='04:02:00'
SELECT RIGHT(convert(varchar, #time, 100), 8)
It produces output:
4:02AM
please help ..
Thanks
You can use:
DECLARE #dt DATETIME
SET #dt = GETDATE()
SELECT CONVERT(varchar(5),#dt,108)
This query gives result in the format 'HH:mm'.
Hope it helps.
DECLARE #time datetime
set #time ='04:02:00'
SELECT LEFT(RIGHT(convert(varchar, #time, 100), 8), 6)
You can use DATEPART and concatenate from there:
SELECT
RIGHT('00' + CONVERT(VARCHAR(2), DATEPART(HOUR, #time)), 2) + ':'
+ RIGHT('00' + CONVERT(VARCHAR(2), DATEPART(MINUTE, #time)), 2)
Notice the RIGHT('00' + ..., 2), this is to pad the hour or minute part with leading zeroes so that it'll be two characters long, e.g 4 becomes 04.

Convert decimal time to hours and minutes

Been struggling with this and can't seem to find the right answer, although there are plenty of mentions for converting, but nothing specific is working.
I need to convert a time with data type of float into hours and minutes. So 13.50 as 13.30. The data type as fixed as float in DB so cannot change. DB is SQL Server 2008R2
Have tried:
cast(cast(floor(fdsViewTimesheet.perStandardHours) as
float(2))+':'+cast(floor(100*(
fdsViewTimesheet.perStandardHours - floor(fdsViewTimesheet.perStandardHours)))as
float(2)) as time) AS STANDARD_HOURS
But I get error message "Explicit conversion from data type real to time is not allowed" Have tried as char instead of as float but query hangs.
What am I doing wrong? I just want to convert a float value into hours and minutes.
Would be grateful if someone could point me in the right direction.
You can try:
DECLARE #HOURS decimal(7,4) = 20.5599
SELECT CAST(CONVERT(VARCHAR,DATEADD(SECOND, #HOURS * 3600, 0),108) AS TIME)
output : 20:33:35
But remember : Type Time in MSSQL only under 24hrs
If you want greater than 24hrs, try:
DECLARE #HOURS decimal(7,4) = 25.5599
SELECT
RIGHT('0' + CAST (FLOOR(#HOURS) AS VARCHAR), 2) + ':' +
RIGHT('0' + CAST(FLOOR((((#HOURS * 3600) % 3600) / 60)) AS VARCHAR), 2) + ':' +
RIGHT('0' + CAST (FLOOR((#HOURS * 3600) % 60) AS VARCHAR), 2)
output : 25:33:35
-- Update
Decimal minutes to more than 24hrs
DECLARE #MINUTES decimal(7,4) = 77.9
SELECT
RIGHT('0' + CAST (FLOOR(COALESCE (#MINUTES, 0) / 60) AS VARCHAR (8)), 2) + ':' +
RIGHT('0' + CAST (FLOOR(COALESCE (#MINUTES, 0) % 60) AS VARCHAR (2)), 2) + ':' +
RIGHT('0' + CAST (FLOOR((#MINUTES* 60) % 60) AS VARCHAR (2)), 2);
output: 01:17:54
This should work for you
DECLARE #f [real]
SET #f = 13.50
SELECT DATEADD(mi, (#f - FLOOR(#f)) * 60, DATEADD(hh, FLOOR(#f), CAST ('00:00:00' AS TIME)))
DECLARE #f FLOAT = 13.5;
SELECT CONVERT(TIME(0), DATEADD(MINUTE, 60*#f, 0));
Or if you just want hh:mm as a string:
SELECT CONVERT(CHAR(5), DATEADD(MINUTE, 60*#f, 0), 108);
Just be careful if you have values >= 24.
How about you convert to minutes and add to the 00:00 time like so:
DECLARE #c datetime
select #c = dateadd(mi,fdsViewTimesheet.perStandardHours*60,'00:00')
If you wanted to do it in the statement with Time only:
select CONVERT(TIME,dateadd(mi,fdsViewTimesheet.perStandardHours*60,'00:00') )
If you have values that are larger than 24 hours, then the standard datetime and time types in sql cannot hold these. They are limited to holding 24 hour ranges.
What you would need to do is store the time representation in a string for example like so:
select cast(floor(fdsViewTimesheet.perStandardHours) as varchar(10)) + ':' + cast(FLOOR( (fdsViewTimesheet.perStandardHours - floor(fdsViewTimesheet.perStandardHours))*60)as varchar(2))

T-SQL formatting calculated column as time

Could use guru help on this one. Trying to calculate the time between two datetime values and show as time in a T-SQL query...
SELECT arrivalDate - departDate AS timeToComplete
This should always be less than 24 hours. But who knows what the user may actually input?
I have been trying something like this with no resutls.
SELECT
CAST(time(7),
CONVERT(datetime, arrivalDate - departDate) AS timeToComplete) AS newTime,
Instead of showing results as 1:23:41 as an example, is there a way to show results like:
0D, 1H, 23M, 33S.
Thanks for any guidance on this.
You could get the total difference in seconds and then keep taking the largest part out of that. I.e., start with Days, then hours, minutes and seconds.
DECLARE #arrivalDate DATETIME = '2013-01-19 23:59:59'
DECLARE #departDate DATETIME = '2013-01-25 11:52:30'
DECLARE #SecondsDifference INT = DATEDIFF(SECOND, #arrivalDate, #departDate)
DECLARE #DayDifference INT = #SecondsDifference / 86400
DECLARE #HourDifference INT = (#SecondsDifference - (#DayDifference * 86400)) / 3600
DECLARE #MinDifference INT = (#SecondsDifference - (#DayDifference * 86400) - (#HourDifference * 3600)) / 60
DECLARE #SecDifference INT = (#SecondsDifference - (#DayDifference * 86400) - (#HourDifference * 3600) - (#MinDifference * 60))
I've done it here using variables for clarity, but you could work this into a single query. DATEDIFF wont work for the smaller chunks of the difference until you remove the larger ones because you'd get the totals. For example:
DATEDIFF(HOUR, #arrivalDate, #departDate)
would return the total number of hours, not the hours less the whole days.
Just to be different :)
Try to use this approach:
declare #date1 datetime;
declare #date2 datetime;
set #date1 = '2012-05-01 12:00:000'
set #date2 = '2012-05-01 18:00:000'
SELECT
STUFF(
STUFF(
STUFF(
RIGHT(CONVERT(NVARCHAR(19), CONVERT(DATETIME, DATEADD(second, DATEDIFF(S, #date1, #date2), '20000101')), 120), 11),
3, 1, 'D, '),
8, 1, 'H, '),
13, 1, 'M, ') + ' S';
Finally found a great solution at this link,
SQL - Seconds to Day, Hour, Minute, Second
thanks for the help though folks, it got me further into this issue and searching for the right info.

Resources