83 lines
2.0 KiB
Go
83 lines
2.0 KiB
Go
package timerange
|
|
|
|
import (
|
|
"math"
|
|
"time"
|
|
)
|
|
|
|
type TimeRange struct {
|
|
Head time.Time
|
|
Tail time.Time
|
|
}
|
|
|
|
func (t *TimeRange) HeadAddDay(d time.Duration) TimeRange {
|
|
return TimeRange{
|
|
Head: t.Head.Add(d),
|
|
Tail: t.Tail,
|
|
}
|
|
}
|
|
|
|
func (t *TimeRange) TailAddDay(d time.Duration) TimeRange {
|
|
return TimeRange{
|
|
Head: t.Head,
|
|
Tail: t.Tail.Add(d),
|
|
}
|
|
}
|
|
|
|
func (t *TimeRange) TotalDays() int64 {
|
|
return int64(math.Floor(float64(t.Tail.Sub(t.Head).Hours() / 24)))
|
|
}
|
|
|
|
func (t *TimeRange) SplitByMinute(minute int64) []TimeRange {
|
|
count := int(t.Tail.Sub(t.Head)/time.Minute) / int(minute)
|
|
var split = make([]TimeRange, 0, count)
|
|
temp := t.Head
|
|
if t.Tail.After(temp) {
|
|
sub := temp.Add(time.Duration(minute) * time.Minute)
|
|
if sub.After(t.Tail) { //防止tail超出设定值
|
|
sub = t.Tail
|
|
}
|
|
subRange := TimeRange{ //一个切片
|
|
Head: temp,
|
|
Tail: sub,
|
|
}
|
|
split = append(split, subRange)
|
|
temp = sub
|
|
}
|
|
return split
|
|
}
|
|
|
|
// LocDayRange 本地当日时间范围
|
|
func LocDayRange(position time.Time) TimeRange {
|
|
head := time.Date(position.Year(), position.Month(), position.Day(), 0, 0, 0, 0, position.Location()).In(time.Local)
|
|
tail := head.AddDate(0, 0, 1)
|
|
return TimeRange{
|
|
Head: head,
|
|
Tail: tail,
|
|
}
|
|
}
|
|
|
|
// LocDayRange 本地当月时间范围
|
|
func LocMonthRange(position time.Time) TimeRange {
|
|
head := time.Date(position.Year(), position.Month(), 1, 0, 0, 0, 0, position.Location()).In(time.Local)
|
|
tail := head.AddDate(0, 1, 0)
|
|
return TimeRange{
|
|
Head: head,
|
|
Tail: tail,
|
|
}
|
|
}
|
|
|
|
func RecentMinute(tim time.Time, scaleMinute int64) time.Time {
|
|
minute := int64(tim.Minute())
|
|
lave := minute % scaleMinute
|
|
formatMinute := minute - lave
|
|
return time.Date(tim.Year(), tim.Month(), tim.Day(), tim.Hour(), int(formatMinute), 0, 0, tim.Location())
|
|
}
|
|
|
|
func RecentSecond(tim time.Time, scaleSecond int64) time.Time {
|
|
second := int64(tim.Second())
|
|
lave := second % scaleSecond
|
|
formatSecond := second - lave
|
|
return time.Date(tim.Year(), tim.Month(), tim.Day(), tim.Hour(), tim.Minute(), int(formatSecond), 0, tim.Location())
|
|
}
|