标签:格式化 int fmt return Golang helpers func time 相关
相对于 PHP
而言,Golang
里面的获取时间应该说是很不方便有木有。因此,特意封装了以下项目中常用到的获取时间相关的函数。
// 时间戳相关package helpersimport "time"// 获取当前时间|字符串func GetTime() string { return time.Now().Format("2006-01-02 15:04:05") }// 获取当前日期|字符串func GetDate() string { return time.Now().Format("2006-01-02") }// 获取相对时间|字符串func GetRelativeTime(years int, months int, days int) string { return time.Now().AddDate(years, months, days).Format("2006-01-02 15:04:05") }// 获取当前时间戳|秒func GetTimestamp() int64 { return time.Now().UnixNano() / 1e9}// 获取当前时间戳|毫秒func GetMicroTimestamp() int64 { return time.Now().UnixNano() / 1e6}// 获取相对时间戳|秒func GetRelativeTimestamp(years int, months int, days int) int64 { timeStr := GetRelativeTime(years, months, days) timeLocation, _ := time.LoadLocation("Asia/Chongqing") timeParse, _ := time.ParseInLocation("2006-01-02 15:04:05", timeStr, timeLocation) return timeParse.Unix() }// 获取相对日期[00:00:00]时间戳|秒func GetZeroTimestamp(years int, months int, days int) int64 { timeStr := time.Now().AddDate(years, months, days).Format("2006-01-02 00:00:00") timeLocation, _ := time.LoadLocation("Asia/Chongqing") timeParse, _ := time.ParseInLocation("2006-01-02 15:04:05", timeStr, timeLocation) return timeParse.Unix() }// 时间字符串转时间戳|秒func TimeToTimestamp(timeStr string) int64 { timeLocation, _ := time.LoadLocation("Asia/Chongqing") timeParse, _ := time.ParseInLocation("2006-01-02 15:04:05", timeStr, timeLocation) return timeParse.Unix() }
测试如下:
package mainimport ( "fmt" "helpers")func main() { fmt.Println(helpers.GetTime()) // 2018-11-06 18:39:08 fmt.Println(helpers.GetDate()) // 2018-11-06 fmt.Println(helpers.GetRelativeTime(0, 0, -1)) // 2018-11-05 18:39:08 fmt.Println(helpers.GetTimestamp()) // 1541500748 fmt.Println(helpers.GetMicroTimestamp()) // 1541500748857 fmt.Println(helpers.GetRelativeTimestamp(0, 0, -1)) // 1541414348 fmt.Println(helpers.GetZeroTimestamp(0, 0, -1)) // 1541347200 fmt.Println(helpers.TimeToTimestamp("2018-11-06 18:30:00")) // 1541500200}
标签:格式化,int,fmt,return,Golang,helpers,func,time,相关 来源: https://blog.51cto.com/u_13640989/2728627
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。