初始化
This commit is contained in:
53
utils/utils.go
Normal file
53
utils/utils.go
Normal file
@@ -0,0 +1,53 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/gogf/gf/v2/errors/gcode"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
"reflect"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ValidStructPtr 验证是否为结构体指针
|
||||
func ValidStructPtr(req any) (err error) {
|
||||
//验证请求参数必须为指针
|
||||
var (
|
||||
reflectValue reflect.Value
|
||||
reflectKind reflect.Kind
|
||||
)
|
||||
if v, ok := req.(reflect.Value); ok {
|
||||
reflectValue = v
|
||||
} else {
|
||||
reflectValue = reflect.ValueOf(req)
|
||||
}
|
||||
|
||||
reflectKind = reflectValue.Kind()
|
||||
if reflectKind != reflect.Ptr {
|
||||
err = gerror.NewCode(gcode.CodeInvalidParameter, `the parameter "req" for function Find should type of *struct/*[]struct`)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// GetMonthToday 获取N个月前的某日
|
||||
func GetMonthToday(t time.Time, month int) time.Time {
|
||||
// today
|
||||
fmt.Printf("today: [%s]\n", t)
|
||||
// 判断天数范围 小于等于28天的计算,覆盖大多数情况
|
||||
if t.Day() <= 28 {
|
||||
return t.AddDate(0, -month, 0)
|
||||
}
|
||||
// 月份的天数数组
|
||||
monthDay := [13]int{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
|
||||
// 计算目标所在日期
|
||||
target := t.AddDate(0, 0, 1-t.Day()).AddDate(0, -month, 0)
|
||||
// 计算当月最大天数
|
||||
targetDay := monthDay[target.Month()]
|
||||
// 计算闰年
|
||||
if target.Month() == time.February && (target.Year()%400 == 0 || (target.Year()%100 != 0 && target.Year()%4 == 0)) {
|
||||
targetDay++
|
||||
}
|
||||
if t.Day() > targetDay {
|
||||
return target.AddDate(0, 0, targetDay-1)
|
||||
}
|
||||
return target.AddDate(0, 0, t.Day()-1)
|
||||
}
|
||||
Reference in New Issue
Block a user