feat: timer 包新增部分获取 分、日、月、年 开始结束时间函数,以及快捷创建时间窗口时间段的函数

This commit is contained in:
kercylan98 2023-09-23 11:25:46 +08:00
parent fb7839d3e6
commit 05f0016b7e
3 changed files with 74 additions and 0 deletions

View File

@ -131,3 +131,43 @@ func GetDayLast(t time.Time) time.Time {
func GetYesterdayLast(t time.Time) time.Time {
return GetDayLast(GetYesterday(t))
}
// GetMinuteStart 获取一个时间的 0 秒
func GetMinuteStart(t time.Time) time.Time {
return time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), 0, 0, time.Local)
}
// GetMinuteEnd 获取一个时间的 59 秒
func GetMinuteEnd(t time.Time) time.Time {
return GetMinuteStart(t).Add(time.Minute - time.Nanosecond)
}
// GetHourStart 获取一个时间的 0 分 0 秒
func GetHourStart(t time.Time) time.Time {
return time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), 0, 0, 0, time.Local)
}
// GetHourEnd 获取一个时间的 59 分 59 秒
func GetHourEnd(t time.Time) time.Time {
return GetHourStart(t).Add(time.Hour - time.Nanosecond)
}
// GetMonthStart 获取一个时间的月初
func GetMonthStart(t time.Time) time.Time {
return time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, time.Local)
}
// GetMonthEnd 获取一个时间的月末
func GetMonthEnd(t time.Time) time.Time {
return GetMonthStart(t).AddDate(0, 1, -1)
}
// GetYearStart 获取一个时间的年初
func GetYearStart(t time.Time) time.Time {
return time.Date(t.Year(), 1, 1, 0, 0, 0, 0, time.Local)
}
// GetYearEnd 获取一个时间的年末
func GetYearEnd(t time.Time) time.Time {
return GetYearStart(t).AddDate(1, 0, -1)
}

View File

@ -11,6 +11,25 @@ func NewPeriod(start, end time.Time) Period {
return Period{start, end}
}
// NewPeriodWindow 创建一个特定长度的时间窗口
func NewPeriodWindow(t time.Time, size time.Duration) Period {
var start time.Time
if size < time.Minute {
start = t
} else {
start = t.Truncate(time.Minute)
}
end := start.Add(size)
return Period{start, end}
}
// NewPeriodWindowWeek 创建一周长度的时间窗口,从周一零点开始至周日 23:59:59 结束
func NewPeriodWindowWeek(t time.Time) Period {
var start = GetMondayZero(t)
end := start.Add(Week)
return Period{start, end}
}
// NewPeriodWithTimeArray 创建一个时间段
func NewPeriodWithTimeArray(times [2]time.Time) Period {
return NewPeriod(times[0], times[1])

View File

@ -0,0 +1,15 @@
package times_test
import (
"fmt"
"github.com/kercylan98/minotaur/utils/times"
"testing"
"time"
)
func TestNewPeriodWindow(t *testing.T) {
cur := time.Now()
fmt.Println(cur)
window := times.NewPeriodWindow(cur, times.Day)
fmt.Println(window)
}