github.com/angenalZZZ/gofunc@v0.0.0-20210507121333-48ff1be3917b/f/time_frame.go (about) 1 package f 2 3 import ( 4 "time" 5 ) 6 7 // TimeFrame - [Since ~ Until) eg. [1, 15) included 1, not included 15 8 type TimeFrame struct { 9 Since, Until *TimeStamp 10 Data []byte 11 } 12 13 func NewTimeFrame(since, until time.Time) *TimeFrame { 14 t := &TimeFrame{ 15 Since: TimeFrom(since, true), 16 Until: TimeFrom(until, true), 17 Data: make([]byte, 0), 18 } 19 return t 20 } 21 22 func NewTimeFrames(since, until time.Time, duration time.Duration) []*TimeFrame { 23 since, until = time.Unix(since.Unix(), 0).Local(), time.Unix(until.Unix(), 0).Local() 24 a, s := since, make([]*TimeFrame, 0) 25 for a.Before(until) { 26 t := a.Add(duration) 27 if t.Before(until) { 28 s = append(s, NewTimeFrame(a, t)) 29 } else { 30 s = append(s, NewTimeFrame(a, until)) 31 } 32 a = t 33 } 34 return s 35 } 36 37 func (t *TimeFrame) In(t2 time.Time) bool { 38 u := t2.Unix() 39 return t.Since.UnixSecond <= u && u < t.Until.UnixSecond 40 } 41 42 func (t *TimeFrame) String() string { 43 p, _ := EncodeJson(map[string]string{ 44 "Since": t.Since.LocalString(), 45 "Until": t.Until.LocalString(), 46 "Data": string(t.Data), 47 }) 48 return String(p) 49 }