Golang 时间相关格式化


本文摘自网络,作者,侵删。


相对于 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}






本文来自:51CTO博客

感谢作者:寻儒

查看原文:Golang 时间相关格式化


相关阅读 >>

Go官方文档,我们能得到哪些资料?

有没有发现Go 1.17将允许切片转换为数组指针啦?

利用Golang反射机制(reflect)搭建本地leetcode调试器

Golang项目如何部署到linux服务器

Golang 使用 for 输出九九乘法表

Gocn酷Go推荐】Go程序配置利器-viper库

Golang读写文件的几种方法

Golang 写个归并排序

聊聊dubbo-Go-proxy的remotefilter

Golang面向对象编程之构造函数【struct&new】

更多相关阅读请进入《Go》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...