Calculate business hours between two dates

前端 未结 14 1359
被撕碎了的回忆
被撕碎了的回忆 2020-11-27 05:06

How can I calculate business hours between two dates? For example we have two dates; 01/01/2010 15:00 and 04/01/2010 12:00 And we have working hours 09:00 to 17:00 in weekda

14条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 05:26

    Another way of thinking, the below function work correctly if your first day of week is Monday otherwise you should change related lines including (6,7) to your local weekend's days

    create function fn_worktime(@Datetime1 DateTime,@Datetime2 DateTime)
    Returns BigInt
    as
    Begin
        Declare 
                @Date1 Date, 
                @Date2 Date,
                @DateIndex Date,
                @minutes int,
                @lastDayMinutes int,
                @StartTime int , --in minutes
                @FinishTime int ,--in minutes
                @WorkDayLong int --in minutes
    
        Set @StartTime  =8 * 60 + 30 -- 8:30
        Set @FinishTime =17* 60 + 30 -- 17:30
        Set @WorkDayLong =@FinishTime - @StartTime  
    
        Set @Date1 = Convert(Date,@DateTime1)
        Set @Date2 = Convert(Date,@DateTime2)
        Set @minutes=DateDiff(minute,@DateTime1,DateAdd(MINUTE,@FinishTime ,convert(DateTime,@Date1)))
        if @minutes<0 OR DatePart(dw,@Date1) in (6,7)  -- you can even check holdays here. '(6 Saturday,7 Sunday) according to SET DATEFIRST 1'
            Set @minutes=0
    
        Set @DateIndex=DateAdd(day,1,@Date1)
        While @DateIndex<@Date2
        Begin
            if DatePart(dw,@DateIndex) not in (6,7)  -- you can even check holdays here. '(6 Saturday,7 Sunday) according to SET DATEFIRST 1'
                set @minutes=@minutes+@WorkDayLong 
            Set @DateIndex=DateAdd(day,1,@DateIndex)
        End
        if DatePart(dw,@DateIndex) not in (6,7)  -- you can even check holdays here
        Begin
            set @lastDayMinutes=DateDiff(minute,DateAdd(MINUTE ,@StartTime ,convert(DateTime,@Date2)),@DateTime2)
            if @lastDayMinutes>@WorkDayLong 
                set @lastDayMinutes=@WorkDayLong 
            if @Date1<>@Date2   
                set @minutes=@minutes+@lastDayMinutes
            Else
                Set @minutes=@minutes+@lastDayMinutes-@WorkDayLong 
    
        End
        return @minutes
    End
    

提交回复
热议问题