常用类型及数据操作方法
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 

126 lines
3.0 KiB

package helper
import (
"strconv"
"time"
)
func FormatDateTime(str string) string {
date, err := strconv.ParseInt(str, 10, 64)
if err != nil {
return ""
}
return time.Unix(date, 0).Format("2006-01-02 15:04:05")
}
func FormatDate(str string) string {
date, err := strconv.ParseInt(str, 10, 64)
if err != nil {
return ""
}
return time.Unix(date, 0).Format("2006-01-02")
}
// 获取当天开始时间戳
func GetTodayStartTimeStamp() int64 {
var reserveTime time.Time
// loc, _ := time.LoadLocation(time.Location.String())
date := time.Now().Format("2006-01-02")
reserveTime, _ = time.ParseInLocation("2006-01-02", date, time.Local)
return reserveTime.Unix()
}
// 获取当天结束时间戳
func GetTodayEndTimeStamp() int64 {
var reserveTime time.Time
// loc, _ := time.LoadLocation("Asia/Shanghai")
date := time.Now().Format("2006-01-02")
reserveTime, _ = time.ParseInLocation("2006-01-02 15:04:05", date+" 23:59:59", time.Local)
return reserveTime.Unix()
}
// 获取本周开始时间戳
func GetWeekStartTimeStamp() int64 {
var reserveTime time.Time
now := time.Now()
loc, _ := time.LoadLocation("Asia/Shanghai")
offset := int(time.Monday - now.Weekday())
if offset > 0 {
offset = -6
}
weekStartDate := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, offset)
weekMonday := weekStartDate.Format("2006-01-02")
reserveTime, _ = time.ParseInLocation("2006-01-02", weekMonday, loc)
return reserveTime.Unix()
}
// 获取当月开始时间戳
func GetMonthStartTimeStamp() int64 {
var reserveTime time.Time
loc, _ := time.LoadLocation("Asia/Shanghai")
date := time.Now().Format("2006-01")
reserveTime, _ = time.ParseInLocation("2006-01", date, loc)
return reserveTime.Unix()
}
// RFC3339ToCSTLayout convert rfc3339 value to china standard time layout
func RFC3339ToCSTLayout(value string) (string, error) {
var (
cst *time.Location
)
var err error
if cst, err = time.LoadLocation("Asia/Shanghai"); err != nil {
panic(err)
}
ts, err := time.Parse(time.RFC3339, value)
if err != nil {
return "", err
}
return ts.In(cst).Format("2006-01-02 15:04:05"), nil
}
// 具体日期时间转时间戳
func DatetimeToUnix(value string) int64 {
loc, _ := time.LoadLocation("Asia/Shanghai")
reserveTime, _ := time.ParseInLocation("2006-01-02 15:04:05", value, loc)
return reserveTime.Unix()
}
// 具体时间戳转年龄
func CalculateAge(birthTimestamp int64) int {
// 将时间戳转换为 time.Time 对象
birthTime := time.Unix(birthTimestamp, 0)
currentTime := time.Now()
// 获取出生和当前的年、月、日
birthYear := birthTime.Year()
currentYear := currentTime.Year()
birthMonth := int(birthTime.Month())
currentMonth := int(currentTime.Month())
birthDay := birthTime.Day()
currentDay := currentTime.Day()
// 计算初步年龄
age := currentYear - birthYear
// 如果当前月份小于出生月份,或者月份相同但当前日期小于出生日期,则年龄减1
if currentMonth < birthMonth || (currentMonth == birthMonth && currentDay < birthDay) {
age--
}
return age
}