How to split minutes into days, hours and minutes in tsql - sql-server

I have a column which consist of minutes. Is there any simple way to split minutes column into one column which shows days, hours, minutes only?
DURATION
-----------
67 ==> 1 hour, 7 minutes
1507 ==> 1 day, 1 hour, 7 minutes
23 ==> 23 minutes
I googled for solution but I didn't find any solution similar for me. I want to show this in a report but trying to find how can I solve this column looks meaningfully. Duration column's calculation like this.
avg(datediff(MINUTE, ei.SentDate, eo.SentDate)) over(partition by ei.mailbox) as DURATION

A google search landed me here http://www.sqlservercentral.com/Forums/Topic490411-8-1.aspx
and It says... which I just tested working ...
Declare #theMinutes int
Set #theMinutes = 67
Select #theMinutes / 1440 as NoDays -- 1440 minutes per day
, (#theMinutes % 1440) / 60 as NoHours -- modulo 1440
, (#theMinutes % 60) as NoMinutes -- modulo 60

create FUNCTION fun_Date_Friendly (#minutes int)
RETURNS nvarchar(100)
AS
BEGIN
return CASE
when #minutes < 60 then cast( #minutes as varchar(10)) + ' Min'
when #minutes < 1440 then cast(#minutes/60 as varchar(10)) + ' Hr, ' + cast(#minutes%60 as varchar(10)) + ' Min'
else cast(#minutes/(1440 ) as varchar(10)) + ' Days, ' + cast((#minutes%1440 )/60 as varchar(10)) + ' Hr, ' + cast(((#minutes%1440 )%60) as varchar(10)) + ' Min'
end
end
go
then just pass minutes to function
select dbo.fun_Date_Friendly(20) val

Related

converting int to hh:mm format

I have separate integers for hours and minutes and i need to find a way to get the total number of hours followed by minutes preferably in a HH:MM format. The issue that i'm facing is when the minutes are less than ten there is no leading zero and i am doing this for reporting reasons and so would love to be able to do something like
Total Hours worked
102:06 to represent 102 hours and 6 minutes
DECLARE #hours INT = 102
declare #minutes int = 6
SELECT
CONCAT(CAST (SUM((#hours*60)+#minutes)/60 AS VARCHAR(5)) , ':' , CAST (SUM((#hours*60)+#minutes)%60 AS VARCHAR(2)))
In SQL Server, you can do:
select concat(hours, ':',
right('00' + minutes, 2)
)
Another method would be:
select concat(hours, ':',
right(convert(varchar(255), 100 + minutes), 2)
)
Just another similar option using format()
Example
DECLARE #hours INT = 102
declare #minutes int = 6
Select concat(#hours,format(#minutes,':00'))
Returns
102:06

Convert HHH:MM:SS to seconds

From the source database, I am getting HH:MM:SS as 832:24:12
Currently I am using below statement which is working fine for most of the cases hh:mm:ss but it fails when hours are more than 99
ISNULL(LEFT(COLUMN,2) * 3600 + RIGHT(LEFT(COLUMN,5),2) * 60 + RIGHT(COLUMN, 2) ,0)
Just another option with a small tweak to your original
Example
Declare #V varchar(50) = '832:24:12'
Select (left(#V,charindex(':',#V)-1)*3600) + (left(right(#V,5),2)*60) + right(#v,2)
Returns
2996652
You can use a tricky solution using PARSENAME() function.
DECALRE #Hours INT = 0, #Minutes INT = 0 , #Seconds INT = 0
SELECT #Hours = PARSENAME(REPLACE('832:24:12'+':00', ':', '.'),4),
#Minutes = PARSENAME(REPLACE('832:24:12'+':00', ':', '.'),3),
#Seconds = PARSENAME(REPLACE('832:24:12'+':00', ':', '.'),2)
SELECT #Hours * 3600 + #Minutes * 60 + #Seconds as TotalSeconds
I am replacing ':' with '.' character after appending dummy sequence of characters ':00' for PARSENAME() function to work by splitting into delimitted data.
For table query
SELECT PARSENAME(REPLACE(ISNULL(ColumnName + ':00',0), ':', '.'),4) * 3600 +
PARSENAME(REPLACE(ISNULL(ColumnName + ':00',0), ':', '.'),3) * 60 +
PARSENAME(REPLACE(ISNULL(ColumnName + ':00',0), ':', '.'),2) As TotalSecs
FROM TableName
This of a guess, however...
CREATE TABLE #Test (TimeString varchar(10))
INSERT INTO #Test
VALUES ('832:24:12')
SELECT TimeString,
(LEFT(TimeString, H.CI - 1) * 3600) + (SUBSTRING(TimeString,H.CI +1, M.CI - H.CI -1) * 60) + (RIGHT(TimeString, LEN(TimeString) - M.CI))
FROM #Test T
CROSS APPLY (VALUES(CHARINDEX(':',TimeString))) H(CI)
CROSS APPLY (VALUES(CHARINDEX(':',TimeString, H.CI+1))) M(CI);
DROP TABLE #Test;
Hours can be the leftwards chars minus 6 positions to take into account the positions for minutes and seconds in the string (:##:##).
The minutes can accessed by taking the left 2, of the rightmost 5 chars.
The seconds are the right 2 chars.
Ex:
DECLARE #tempval varchar(100) = '832:24:12'
SELECT LEFT(#tempval, LEN(#tempval) - 6) * 3600
+LEFT(RIGHT(#tempval, 5), 2) * 60
+RIGHT(#tempval, 2)
Returns
2996652

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 decimal to time 6.80 =7.20 hrs in SQL [duplicate]

This question already has answers here:
Convert decimal time to hours and minutes
(4 answers)
Closed 9 years ago.
Please help me to do this
decimal 6.80 should equal to 7.20 hours
DECLARE #R1 decimal(4,2);
DECLARE #R2 decimal(4,2);
declare #Type1 decimal(4,2);
declare #Type2 decimal(4,2);
DECLARE #R1Time decimal(4,2);
DECLARE #R2Time decimal(4,2);
SET #R1=2.5
SET #R2=3.5
SET #Type1=17;
SET #Type2=7;
SET #R1Time=(FORMAT((ISNULL(60.0/NULLIF(#R1,0),0)),'N2'))
SET #R2Time=(FORMAT((ISNULL(60.0/NULLIF(#R2,0),0)),'N2'))
SELECT #R1Time as R1Min
SELECT #R2Time as R2Min
SELECT FORMAT(((#Type1*#R1Time)/60.0),'N2') R1Hrs -- 6.80 hours this = 24*17=408/60
SELECT FORMAT(((#Type2*#R2Time)/60.0),'N2') R2Hrs
SELECT CONVERT(CHAR(5), DATEADD(MINUTE, 60*(convert(decimal(4,2),FORMAT(((#Type1*#R1Time)/60.0),'N2'))), 0), 108);--6.48 hours
6.80 hours this = 24*17=408/60 this should be 7.20 hours not 6.48 is it?. Did I am wrong please help me thanks
#R1 is how many in an hour 60/2.5 =24min per Type1 and 17 Type1 is 17*24 =408 min then convert to time –
So what you are saying is that the number before the decimal seperator is correct (in hours) and the number after the decimal seperator is in the absolute amount of minutes?
Then in pseudocode you can do something like this:
INPUT = 6.80
HOURS = FLOOR(INPUT)
DECIMALS = (INPUT - HOURS) * 100
if ( DECIMALS > 60 )
{
HOURS = HOURS + 1
MINUTES = DECIMALS - 60
}
// Now hours and minutes are in the way you intended
Now all you have to do is convert this pseudocode into SQL code.
In function form, this would look something like this (I wrote this by heart so beware for typo's/ errors):
CREATE FUNCTION ChangeTime
-- Input current time decimal
(#CurrentTime decimal(2,1) )
RETURNS decimal(2,1) -- New time
AS
BEGIN
DECLARE #Hours int, #Minutes int;
SET #Hours = FLOOR(#CurrentTime);
SET #Minutes = (#CurrentTime - #Hours)*100;
IF #Minutes >= 60
BEGIN
SET #Hours = #Hours + 1; -- New hours
SET #Minutes = #Minutes - 60; -- New minutes
END
RETURN ( #Hours + (#Minutes/100) ) -- New (corrected) time
END
On the other hand, if you mean: I need to convert the decimals such that 6.50 becomes 6 hours and 30 minutes and 6.80 becomes 6 hours and 48 minutes, then we can change the function to the following:
CREATE FUNCTION ChangeTime
-- Input current time decimal
(#CurrentTime decimal(2,1) )
RETURNS decimal(2,1) -- New time
AS
BEGIN
DECLARE #Hours int, #Minutes int;
SET #Hours = FLOOR(#CurrentTime);
SET #Minutes = (#CurrentTime - #Hours)*100;
SET #Minutes = (#Minutes / 100) * 60; -- New minutes
RETURN ( #Hours + (#Minutes/100) ) -- New (corrected) time
END
If both of these functions do not get the desired result, then please update your question with an explanation of what you exactly want to achieve.
Good luck!
declare #hour decimal(6,2) = 6.8
select floor(#hour) + floor(#hour%1/.6) + #hour%1%.6
Result:
7.20
If you want it as a function:
CREATE FUNCTION f_convert(#hour decimal(6,2))
RETURNS decimal(6,2)
AS
BEGIN
RETURN floor(#hour) + floor(#hour%1/.6) + #hour%1%.6
END
Test(sqlserver 2008+):
SELECT dbo.f_convert(hour)
FROM (values (6.8),(3.9),(.59)) x(hour)
Result:
7.20
4.30
0.59

How to convert number of minutes to hh:mm format in TSQL?

I have a select query that has DURATION column to calculate number of Minutes . I want to convert those minutes to hh:mm format.
Duration has values like 60, 120,150
For example:
60 becomes 01:00 hours
120 becomes 02:00 hours
150 becomes 02:30 hours
Also, this is how I retrieve DURATION (Minutes)
DATEDIFF(minute, FirstDate,LastDate) as 'Duration (Minutes)'
You can convert the duration to a date and then format it:
DECLARE
#FirstDate datetime,
#LastDate datetime
SELECT
#FirstDate = '2000-01-01 09:00:00',
#LastDate = '2000-01-01 11:30:00'
SELECT CONVERT(varchar(12),
DATEADD(minute, DATEDIFF(minute, #FirstDate, #LastDate), 0), 114)
/* Results: 02:30:00:000 */
For less precision, modify the size of the varchar:
SELECT CONVERT(varchar(5),
DATEADD(minute, DATEDIFF(minute, #FirstDate, #LastDate), 0), 114)
/* Results: 02:30 */
This function is to convert duration in minutes to readable hours and minutes format. i.e 2h30m. It eliminates the hours if the duration is less than one hour, and shows only the hours if the duration in hours with no extra minutes.
CREATE FUNCTION [dbo].[MinutesToDuration]
(
#minutes int
)
RETURNS nvarchar(30)
AS
BEGIN
declare #hours nvarchar(20)
SET #hours =
CASE WHEN #minutes >= 60 THEN
(SELECT CAST((#minutes / 60) AS VARCHAR(2)) + 'h' +
CASE WHEN (#minutes % 60) > 0 THEN
CAST((#minutes % 60) AS VARCHAR(2)) + 'm'
ELSE
''
END)
ELSE
CAST((#minutes % 60) AS VARCHAR(2)) + 'm'
END
return #hours
END
To use this function :
SELECT dbo.MinutesToDuration(23)
Results: 23m
SELECT dbo.MinutesToDuration(120)
Results: 2h
SELECT dbo.MinutesToDuration(147)
Results: 2h27m
Hope this helps!
I'm not sure these are the best options but they'll definitely get the job done:
declare #durations table
(
Duration int
)
Insert into #durations(Duration)
values(60),(80),(90),(150),(180),(1000)
--Option 1 - Manually concatenate the values together
select right('0' + convert(varchar,Duration / 60),2) + ':' + right('0' + convert(varchar,Duration % 60),2)
from #Durations
--Option 2 - Make use of the time variable available since SQL Server 2008
select left(convert(time,DATEADD(minute,Duration,0)),5)
from #durations
GO
DECLARE #Duration int
SET #Duration= 12540 /* for example big hour amount in minutes -> 209h */
SELECT CAST( CAST((#Duration) AS int) / 60 AS varchar) + ':' + right('0' + CAST(CAST((#Duration) AS int) % 60 AS varchar(2)),2)
/* you will get hours and minutes divided by : */
For those who need convert minutes to time with more than 24h format:
DECLARE #minutes int = 7830
SELECT CAST(#minutes / 60 AS VARCHAR(8)) + ':' + FORMAT(#minutes % 60, 'D2') AS [Time]
Result:
130:30
This seems to work for me:
SELECT FORMAT(#mins / 60 * 100 + #mins % 60, '#:0#')
Thanks to A Ghazal, just what I needed. Here's a slightly cleaned up version of his(her) answer:
create FUNCTION [dbo].[fnMinutesToDuration]
(
#minutes int
)
RETURNS nvarchar(30)
-- Based on http://stackoverflow.com/questions/17733616/how-to-convert-number-of-minutes-to-hhmm-format-in-tsql
AS
BEGIN
return rtrim(isnull(cast(nullif((#minutes / 60)
, 0
) as varchar
) + 'h '
,''
)
+ isnull(CAST(nullif((#minutes % 60)
,0
) AS VARCHAR(2)
) + 'm'
,''
)
)
end
select convert(varchar(5),dateadd(mi,DATEDIFF(minute, FirstDate,LastDate),'00:00'),114)
In case someone is interested in getting results as
60 becomes 01:00 hours, 120 becomes 02:00 hours, 150 becomes 02:30 hours, this function might help:
create FUNCTION [dbo].[MinutesToHHMM]
(
#minutes int
)
RETURNS varchar(30)
AS
BEGIN
declare #h int
set #h= #minutes / 60
declare #mins varchar(2)
set #mins= iif(#minutes%60<10,concat('0',cast((#minutes % 60) as varchar(2))),cast((#minutes % 60) as varchar(2)))
return iif(#h <10, concat('0', cast(#h as varchar(5)),':',#mins)
,concat(cast(#h as varchar(5)),':',#mins))
end
I would do the following (copy-paste the whole stuff below into immediate window / query window and execute)
DECLARE #foo int
DECLARE #unclefoo smalldatetime
SET #foo = DATEDIFF(minute, CAST('2013.01.01 00:00:00' AS datetime),CAST('2013.01.01 00:03:59' AS datetime)) -- AS 'Duration (Minutes)'
SET #unclefoo = DATEADD(minute, #foo, '2000.01.01')
SELECT CAST(#unclefoo AS time)
#foo stores the value you generate in your question. The "trick" comes by then:
we create a smalldatetime variable (in my case it's yyyy.mm.dd format) and increment it with your int value, then display (or store if you want) the time part only.
declare function dbo.minutes2hours (
#minutes int
)
RETURNS varchar(10)
as
begin
return format(dateadd(minute,#minutes,'00:00:00'), N'HH\:mm','FR-fr')
end
How to get the First and Last Record time different in sql server....
....
Select EmployeeId,EmployeeName,AttendenceDate,MIN(Intime) as Intime ,MAX(OutTime) as OutTime,
DATEDIFF(MINUTE, MIN(Intime), MAX(OutTime)) as TotalWorkingHours
FROM ViewAttendenceReport WHERE AttendenceDate >='1/20/2020 12:00:00 AM' AND AttendenceDate <='1/20/2020 23:59:59 PM'
GROUP BY EmployeeId,EmployeeName,AttendenceDate;
If you want a notation of XX days YY hours and ZZ min, just try:
SELECT
CAST(f.TimeAmount / 1440 AS VARCHAR(8)) + 'd ' +
CAST((f.TimeAmount % 1440) / 60 AS VARCHAR(8)) + 'h ' +
FORMAT(f.TimeAmount % 60, 'D2') + 'min' AS [TIME_TEXT]
FROM
MyTable f

Resources