Go语言开发时间格式化

作者: 小歪子go | 来源:发表于2018-01-10 20:32 被阅读153次

习惯了IOS时间格式化的方式,在go语言开发的时候,在Go语言开发的时候竟然为格式化时间还查了半天资料,看完资料之后,才知道原来go语言时间格式化真心简单

生成时间戳
import "time"
func main {
t := time.Now()
fmt.Println("t:”,t.Unix())
}
t:1498017149 

生成毫秒自己去换算,最好自己写一个工具类

当前时间
import (
    "fmt"
    "time"
)

func main() {
    GetNowTime()

}

func GetNowTime() {
    fmt.Println("This is my first go")
    nowTime := time.Now()
    fmt.Println(nowTime)
    t := nowTime.String()
    timeStr := t[:19]
    fmt.Println(timeStr)
}
输出:
2018-01-10 18:41:32.239449 +0800 CST m=+0.000353463
2018-01-10 18:41:32
时间格式化
func GetTime() string {
    const shortForm = "2006-01-01 15:04:05"
    t := time.Now()
    temp := time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), time.Local)
    str := temp.Format(shortForm)
    fmt.Println(t)
    return str
}
字符串转时间戳
func main() {
    x := "2018-01-09 20:24:20"
    p, _ := time.Parse("2006-01-02 15:04:05", x)
    fmt.Println(p.Unix())
}

output:1515529460
秒、纳秒、毫秒
func main() {
    //testAes()
    //testDes()
    now := time.Now()
    second := now.Unix()
    Nanoseconds := now.UnixNano()
    Millisecond := Nanoseconds / 1000000
    fmt.Printf("second:%d,millisecond:%d,Millisecond:%d", second, Nanoseconds, Millisecond)
}
时间字符串转换成Time
不带时区,返回UTC time
func GetTimeFromStr() {
    const format = "2006-01-02 15:04:05"
    timeStr := "2018-01-09 20:24:20"
    p, err := time.Parse(format, timeStr)
    if err == nil {
        fmt.Println(p)
    }
}

带时区匹配,匹配当前时区的时间
func GetTimeFromStrLoc() {
    loc, _ := time.LoadLocation("Asia/Shanghai")
    const longForm = "Jan 2, 2006 at 3:04pm (MST)"
    t, _ := time.ParseInLocation(longForm, "Jul 9, 2012 at 5:02am (CEST)", loc)
    fmt.Println(t)
    // Note: without explicit zone, returns time in given location.
    const shortForm = "2006-Jan-02"
    t, _ = time.ParseInLocation(shortForm, "2012-Jul-09", loc)
    fmt.Println(t)
}

参考文档

Golang的时间生成,格式化,以及获取函数执行时间的方法
Go语言学习之time包获取当前时间戳

相关文章

  • Go语言开发时间格式化

    习惯了IOS时间格式化的方式,在go语言开发的时候,在Go语言开发的时候竟然为格式化时间还查了半天资料,看完资料之...

  • Go语言标准库之time

    Go语言标准库之time 时间的格式化和解析 格式化 Format Go语言和其他语言的时间格式化的方式不同,Go...

  • Go语言标准库之time

    Go语言标准库之time 时间的格式化和解析 格式化 FormatGo语言和其他语言的时间格式化的方式不同,Go语...

  • 04-枚举常量

    Go语言枚举 c语言中的枚举 Go语言枚举 iota迭代器 Go语言输出函数 fmt.Printf("格式化字符串...

  • go fmt与gofmt命令

    go fmt命令会按照Go语言代码规范格式化指定代码包中的所有Go语言源码文件的代码,所有Go语言源码文件即包括命...

  • 06-输入输出函数-指趣学院

    Go语言fmt包实现了类似C语言printf和scanf的格式化I/O, 格式化动作源自C语言但更简单 输出函数 ...

  • Go语言入坑

    GO语言基础 认识并安装GO语言开发环境 Go语言简介 Go语言是谷歌2009年发布的第二款开源编程语言 go语言...

  • Go语言学习 Day 02

    Go语言学习 [TOC] Day 02 官方文档补充 格式化 注释 命名 分号 Go语言使用分号结尾,但词法分析器...

  • 浅谈Go语言函数与方法的区别

    前段时间,我们实验室用go作为后台开发语言开发了一个web项目,由于这是自己第一次使用go语言进行开发,在开发过程...

  • Go语言入门【二】:为什么要使用Go语言

    Go语言是google推出的新兴后端开发语言,我认识的人里,用了都说好。经过前段时间的学习,做个总结�。 Go语言...

网友评论

    本文标题:Go语言开发时间格式化

    本文链接:https://www.haomeiwen.com/subject/pzhcnxtx.html