123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145 |
- 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()]
- }
|