package timeutils import ( "time" ) var ( monthMap = map[string]string{ "01": "一月", "02": "二月", "03": "三月", "04": "四月", "05": "五月", "06": "六月", "07": "七月", "08": "八月", "09": "九月", "10": "十月", "11": "十一月", "12": "十二月", } weekMap = map[string]string{ "Monday": "星期一", "Tuesday": "星期二", "Wednesday": "星期三", "Thursday": "星期四", "Friday": "星期五", "Saturday": "星期六", "Sunday": "星期日", } ) // ParseLocalDateTime 将日期时间字符串转换为time.Time,dateTime参数如果不是日期时间字符串会panic func ParseLocalDateTime(dateTime string) *time.Time { t, err := time.ParseInLocation(time.DateTime, dateTime, time.Local) if err != nil { panic(err) } return &t } // ParseLocalDateOnly 将日期字符串转换为time.Time,dateTime参数如果不是日期字符串会panic func ParseLocalDateOnly(date string) *time.Time { t, err := time.ParseInLocation(time.DateOnly, date, time.Local) if err != nil { panic(err) } return &t } // ParseNowDateOnly 将当前时间转换为time.Time,仅有日期信息 func ParseNowDateOnly() *time.Time { return ParseLocalDateOnly(FormatNowDateOnly()) } // FormatNowDateTime 将当前时间转化为日期时间格式 func FormatNowDateTime() string { return time.Now().Format(time.DateTime) } // FormatLocalDateTime 将time.Time转化为日期时间格式 func FormatLocalDateTime(t *time.Time) string { if t == nil { return "" } return t.Format(time.DateTime) } // FormatNowDateOnly 将当前时间转化为日期格式 func FormatNowDateOnly() string { return time.Now().Format(time.DateOnly) } // FormatLocalDateOnly 将time.Time转化为日期格式 func FormatLocalDateOnly(t *time.Time) string { if t == nil { return "" } return t.Format(time.DateOnly) } // GetYear 获取time.Time的年 func GetYear(t *time.Time) int { if t == nil { return 0 } year, _ := t.ISOWeek() return year } // GetWeek 获取time.Time的星期 func GetWeek(t *time.Time) int { if t == nil { return 0 } _, week := t.ISOWeek() return week } // DiffNatureDays 计算两个时间相差的天数 func DiffNatureDays(t1str string, t2str string) int { t1 := ParseLocalDateTime(t1str).Unix() t2 := ParseLocalDateTime(t2str).Unix() var secondsOfDay int64 = 86400 if t1 == t2 { return -1 } if t1 > t2 { t1, t2 = t2, t1 } diffDays := 0 secDiff := t2 - t1 if secDiff > secondsOfDay { tmpDays := int(secDiff / secondsOfDay) t1 += int64(tmpDays) * secondsOfDay diffDays += tmpDays } st := time.Unix(t1, 0) et := time.Unix(t2, 0) dateFormatTpl := "20060102" if st.Format(dateFormatTpl) != et.Format(dateFormatTpl) { diffDays += 1 } return diffDays } // GetChinaMonth 获取中文表示的年 func GetChinaMonth(t *time.Time) string { if t == nil { return "" } month := t.Format("01") return monthMap[month] } // GetChinaWeek 获取中文表示的星期 func GetChinaWeek(t *time.Time) string { if t == nil { return "" } week := t.Weekday() return weekMap[week.String()] }