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": "星期日", } ) func ParseLocalDateTime(dateTime string) *time.Time { t, err := time.ParseInLocation(time.DateTime, dateTime, time.Local) if err != nil { panic(err) } return &t } func ParseLocalDateOnly(date string) *time.Time { t, err := time.ParseInLocation(time.DateOnly, date, time.Local) if err != nil { panic(err) } return &t } func ParseNowDateOnly() *time.Time { return ParseLocalDateOnly(FormatNowDateOnly()) } func FormatNowDateTime() string { return time.Now().Format(time.DateTime) } func FormatLocalDateTime(t *time.Time) string { if t == nil { return "" } return t.Format(time.DateTime) } func FormatNowDateOnly() string { return time.Now().Format(time.DateOnly) } func FormatLocalDateOnly(t *time.Time) string { if t == nil { return "" } return t.Format(time.DateOnly) } func GetYear(t *time.Time) int { if t == nil { return 0 } year, _ := t.ISOWeek() return year } func GetWeek(t *time.Time) int { if t == nil { return 0 } _, week := t.ISOWeek() return week } 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 } func GetChinaMonth(t *time.Time) string { if t == nil { return "" } month := t.Format("01") return monthMap[month] } func GetChinaWeek(t *time.Time) string { if t == nil { return "" } week := t.Weekday() return weekMap[week.String()] }