From b5a75220ff45bf120b0e9390621775f69207e57e Mon Sep 17 00:00:00 2001 From: kercylan98 Date: Wed, 26 Apr 2023 20:22:44 +0800 Subject: [PATCH] =?UTF-8?q?=E6=97=B6=E9=97=B4=E5=A4=84=E7=90=86=E8=BE=85?= =?UTF-8?q?=E5=8A=A9=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- utils/times/helper.go | 61 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 utils/times/helper.go diff --git a/utils/times/helper.go b/utils/times/helper.go new file mode 100644 index 0000000..a580b00 --- /dev/null +++ b/utils/times/helper.go @@ -0,0 +1,61 @@ +package times + +import "time" + +// GetMonthDays 获取一个时间当月共有多少天 +func GetMonthDays(t time.Time) int { + t = GetToday(t) + year, month, _ := t.Date() + if month != 2 { + if month == 4 || month == 6 || month == 9 || month == 11 { + return 30 + } + return 31 + } + + if ((year%4 == 0) && (year%100 != 0)) || year%400 == 0 { + return 29 + } + + return 28 +} + +// WeekDay 获取一个时间是星期几 +// - 1 ~ 7 +func WeekDay(t time.Time) int { + t = GetToday(t) + week := int(t.Weekday()) + if week == 0 { + week = 7 + } + + return week +} + +// GetToday 获取一个时间的今天 +func GetToday(t time.Time) time.Time { + return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.Local) +} + +// GetSecond 获取共有多少秒 +func GetSecond(d time.Duration) int { + return int(d / time.Second) +} + +// IsSameDay 两个时间是否是同一天 +func IsSameDay(t1, t2 time.Time) bool { + t1, t2 = GetToday(t1), GetToday(t2) + return t1.Unix() == t2.Unix() +} + +// IsSameHour 两个时间是否是同一小时 +func IsSameHour(t1, t2 time.Time) bool { + return t1.Hour() == t2.Hour() && t1.Day() == t2.Day() && t1.Month() == t2.Month() && t1.Year() == t2.Year() +} + +// GetMondayZero 获取本周一零点 +func GetMondayZero(t time.Time) time.Time { + t = GetToday(t) + weekDay := WeekDay(t) + return t.AddDate(0, 0, 1-weekDay) +}