This commit is contained in:
zyj
2025-09-13 10:22:49 +08:00
commit 002419a7ed
28 changed files with 1888 additions and 0 deletions

75
utils/index.go Normal file
View File

@@ -0,0 +1,75 @@
package utils
import (
"math/rand"
"time"
)
type RandDateParams struct {
Year int
Month int
Day int
}
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
const (
letterBits = 6 // 52个字母需6位2^6=64
letterMask = 1<<letterBits - 1 // 二进制掩码63个1
)
func BoolToInt(b bool) int64 {
if b {
return 1
}
return 0
}
func RandString(n int) string {
b := make([]byte, n)
for i := 0; i < n; {
if idx := int(rand.Int63() & letterMask); idx < len(letters) {
b[i] = letters[idx]
i++
} // 丢弃无效索引,重试
}
return string(b)
}
func RandDate(minAge, maxAge int) RandDateParams {
// 创建本地随机生成器(避免全局 rand.Seed 弃用问题)
r := rand.New(rand.NewSource(time.Now().UnixNano()))
// 计算年份范围(当前年-100岁 到 当前年-18岁
currentTime := time.Now()
currentYear := currentTime.Year()
minYear := currentYear - maxAge
maxYear := currentYear - minAge
// 生成随机年份
year := minYear + r.Intn(maxYear-minYear+1)
// 生成随机月份1-12
month := r.Intn(12) + 1
// 动态计算当月最大天数(考虑闰年)
daysInMonth := 31
switch month {
case 2: // 二月特殊处理
if (year%4 == 0 && year%100 != 0) || year%400 == 0 {
daysInMonth = 29 // 闰年
} else {
daysInMonth = 28 // 平年
}
case 4, 6, 9, 11: // 30 天的月份
daysInMonth = 30
}
// 生成随机日期1 ~ daysInMonth
day := r.Intn(daysInMonth) + 1
return RandDateParams{
Year: year,
Month: month,
Day: day,
}
}