判断时间是否在分段时间内的代码片段
判断时间是否在分段时间内的代码片段
package main

import (
	"fmt"
	"time"
)

type Segment struct {
	BeginTime string
	EndTime   string
}
type TimeSegments [24]uint64

func (s *TimeSegments) In(t time.Time) bool {
	return s[t.Hour()]&(1<<t.Minute()) > 0
}

func SegmentData(timeSegment []Segment) *TimeSegments {
	data := TimeSegments{}
	for _, v := range timeSegment {
		startMinute, endMinute := SegmentTime2Minute(v.BeginTime), SegmentTime2Minute(v.EndTime)
		if startMinute > endMinute {
			endMinute = 1440
		}
		for i := startMinute; i < endMinute; i++ {
			data[i/60] |= 1 << (i % 60)
		}
	}
	return &data
}

func SegmentTime2Minute(stringTime string) int {
	t, _ := time.Parse("15:04", stringTime)
	return t.Hour()*60 + t.Minute()
}

func main() {
	data := SegmentData([]Segment{{
		BeginTime: "02:08",
		EndTime:   "03:13",
	}, {
		BeginTime: "14:13",
		EndTime:   "18:00",
	}})
	for i := range data {
		fmt.Printf("Data[%d]:%b\n", i, data[i])
	}
	now := time.Now()
	for i := now; i.Before(now.AddDate(0,0,2)); i = i.Add(time.Minute) {
		fmt.Printf("[%s]: %t \n", i, data.In(i))
	}
}

Last modified on 2021-12-10