Calculate time difference (only working hours) in minutes between two dates

前端 未结 5 1129
长情又很酷
长情又很酷 2020-12-06 03:30

I need to calculate the number of \"active minutes\" for an event within a database. The start-time is well known.

The complication is that these active minutes sho

5条回答
  •  执笔经年
    2020-12-06 04:15

    I came here looking for an answer to a very similar question - I needed to get the minutes between 2 dates excluding weekends and excluding hours outside of 08:30 and 18:00. After a bit of hacking around, I think i have it sorted. Below is how I did it. thoughts are welcome - who knows, maybe one day I'll sign up to this site :)

    create function WorkingMinutesBetweenDates(@dteStart datetime, @dteEnd datetime)
    returns int
    as
    begin
    
    declare @minutes int
    set @minutes = 0
    
    while @dteEnd>=@dteStart
        begin
    
            if  datename(weekday,@dteStart) <>'Saturday' and  datename(weekday,@dteStart)<>'Sunday'
                and (datepart(hour,@dteStart) >=8 and datepart(minute,@dteStart)>=30 )
                and (datepart(hour,@dteStart) <=17)
    
                begin
                    set @minutes = @minutes + 1
                end     
    
            set @dteStart = dateadd(minute,1,@dteStart)
        end
    
    return @minutes
    end
    go
    

提交回复
热议问题