github.com/artisanhe/tools@v1.0.1-0.20210607022958-19a8fef2eb04/timelib/working_day.go (about)

     1  package timelib
     2  
     3  import (
     4  	"math"
     5  	"time"
     6  )
     7  
     8  const (
     9  	WORKING_DAYS = 5
    10  	WEEKEND_DAYS = 2
    11  	DAY_SECONDS  = 86400
    12  )
    13  
    14  // 根据指定时区获取当天第一秒
    15  func GetTodayFirstSecInLocation(t time.Time, loc *time.Location) time.Time {
    16  	locTime := t.In(loc)
    17  	locTodayMax := time.Date(locTime.Year(), locTime.Month(), locTime.Day(), 0, 0, 0, 0, loc)
    18  	return locTodayMax
    19  }
    20  
    21  // 根据指定时区获取当天最后一秒
    22  func GetTodayLastSecInLocation(t time.Time, loc *time.Location) time.Time {
    23  	locTime := t.In(loc)
    24  	locTodayMax := time.Date(locTime.Year(), locTime.Month(), locTime.Day(), 23, 59, 59, 0, loc)
    25  	return locTodayMax
    26  }
    27  
    28  // 根据指定时区添加 N 个工作日
    29  func AddWorkingDaysInLocation(t time.Time, days int, loc *time.Location) time.Time {
    30  	locTime := t.In(loc)
    31  	weekDay := locTime.Weekday()
    32  	weekends := int(math.Ceil(float64(int(weekDay)+days)/float64(WORKING_DAYS))) - 1
    33  	weekendDays := weekends * WEEKEND_DAYS
    34  	if weekDay == time.Saturday {
    35  		weekendDays -= 1
    36  	}
    37  	realDays := days + weekendDays
    38  	return locTime.AddDate(0, 0, realDays)
    39  }
    40  
    41  // 计算日期偏差
    42  func CountDateDiff(startTime, endTime time.Time, loc *time.Location) int64 {
    43  	return (GetTodayFirstSecInLocation(endTime, loc).Unix() - GetTodayFirstSecInLocation(startTime, loc).Unix()) / DAY_SECONDS
    44  }