今天就跟大家聊聊有關(guān)Golang中如何操作時(shí)間,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
目前創(chuàng)新互聯(lián)公司已為超過千家的企業(yè)提供了網(wǎng)站建設(shè)、域名、網(wǎng)站空間、網(wǎng)站改版維護(hù)、企業(yè)網(wǎng)站設(shè)計(jì)、阜陽網(wǎng)站維護(hù)等服務(wù),公司將堅(jiān)持客戶導(dǎo)向、應(yīng)用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶和合作伙伴齊心協(xié)力一起成長(zhǎng),共同發(fā)展。實(shí)現(xiàn)代碼
package utils import "time" const ( TIMEFORMAT = "20060102150405" NORMALTIMEFORMAT = "2006-01-02 15:04:05" ) // 當(dāng)前時(shí)間 func GetTime() time.Time{ return time.Now() } // 格式化為:20060102150405 func GetTimeString(t time.Time) string { return t.Format(TIMEFORMAT) } // 格式化為:2006-01-02 15:04:05 func GetNormalTimeString(t time.Time) string { return t.Format(NORMALTIMEFORMAT) } // 轉(zhuǎn)為時(shí)間戳->秒數(shù) func GetTimeUnix(t time.Time) int64 { return t.Unix() } // 轉(zhuǎn)為時(shí)間戳->毫秒數(shù) func GetTimeMills(t time.Time) int64 { return t.UnixNano() / 1e6 } // 時(shí)間戳轉(zhuǎn)時(shí)間 func GetTimeByInt(t1 int64) time.Time{ return time.Unix(t1,0) } // 字符串轉(zhuǎn)時(shí)間 func GetTimeByString(timestring string) (time.Time,error){ if timestring == "" { return time.Time{},nil } return time.ParseInLocation(TIMEFORMAT, timestring, time.Local) } // 標(biāo)準(zhǔn)字符串轉(zhuǎn)時(shí)間 func GetTimeByNormalString(timestring string) (time.Time,error){ if timestring == "" { return time.Time{},nil } return time.ParseInLocation(NORMALTIMEFORMAT, timestring, time.Local) } // 比較兩個(gè)時(shí)間大小 func CompareTime(t1 ,t2 time.Time) bool { return t1.Before(t2) } // n小時(shí)后的時(shí)間字符串 func GetNextHourTime(s string, n int64) string { t2, _ := time.ParseInLocation(TIMEFORMAT, s, time.Local) t1 := t2.Add(time.Hour * time.Duration(n)) return GetTimeString(t1) } // 計(jì)算倆個(gè)時(shí)間差多少小時(shí) func GetHourDiffer(start_time, end_time string) float32 { var hour float32 t1, err := time.ParseInLocation(TIMEFORMAT, start_time, time.Local) t2, err := time.ParseInLocation(TIMEFORMAT, end_time, time.Local) if err == nil && CompareTime(t1,t2) { diff := GetTimeUnix(t2) - GetTimeUnix(t1) hour = float32(diff) / 3600 return hour } return hour } // 判斷當(dāng)前時(shí)間是否是整點(diǎn) func Checkhours() bool { _, m, s := GetTime().Clock() if m == s && m == 0 && s == 0 { return true } return false } // 時(shí)間字符串轉(zhuǎn)為標(biāo)準(zhǔn)字符串 func StringToNormalString(t string) string { if !(len(TIMEFORMAT) == len(t) || len(SHORTTIMESTRING) == len(t)) { return t } if len(SHORTTIMESTRING) == len(t) { t += "000000" } if len(TIMEFORMAT) == len(t) { t1,err:= GetTimeByString(t) if err != nil { return t } t = GetTimeString(t1) } return t }