golang时间字符串和时间戳转换

分手后的思念是犯贱 2022-06-02 01:47 488阅读 0赞

1. 获取当前时间字符串和时间戳

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func main() {
  7. now := time.Now().UTC()
  8. // 显示时间格式: UnixDate = "Mon Jan _2 15:04:05 MST 2006"
  9. fmt.Printf("%s\n", now.Format(time.UnixDate))
  10. // 显示时间戳
  11. fmt.Printf("%ld\n", now.Unix())
  12. // 显示时分:Kitchen = "3:04PM"
  13. fmt.Printf("%s\n", now.Format("3:04PM"))
  14. }

更多时间格式

  1. const (
  2. ANSIC = "Mon Jan _2 15:04:05 2006"
  3. UnixDate = "Mon Jan _2 15:04:05 MST 2006"
  4. RubyDate = "Mon Jan 02 15:04:05 -0700 2006"
  5. RFC822 = "02 Jan 06 15:04 MST"
  6. RFC822Z = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone
  7. RFC850 = "Monday, 02-Jan-06 15:04:05 MST"
  8. RFC1123 = "Mon, 02 Jan 2006 15:04:05 MST"
  9. RFC1123Z = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone
  10. RFC3339 = "2006-01-02T15:04:05Z07:00"
  11. RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
  12. Kitchen = "3:04PM"
  13. // Handy time stamps.
  14. Stamp = "Jan _2 15:04:05"
  15. StampMilli = "Jan _2 15:04:05.000"
  16. StampMicro = "Jan _2 15:04:05.000000"
  17. StampNano = "Jan _2 15:04:05.000000000"
  18. )

2. 时间字符串解析成时间格式

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func main() {
  7. timeStr := "2018-01-01"
  8. fmt.Println("timeStr:", timeStr)
  9. t, _ := time.Parse("2006-01-02", timeStr)
  10. fmt.Println(t.Format(time.UnixDate))
  11. }

3. 获取当天零点时间戳

方法1

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func main() {
  7. timeStr := time.Now().Format("2006-01-02")
  8. t, _ := time.Parse("2006-01-02", timeStr)
  9. fmt.Println(t.Format(time.UnixDate))
  10. //Unix返回早八点的时间戳,减去8个小时
  11. timestamp := t.UTC().Unix() - 8*3600
  12. fmt.Println("timestamp:", timestamp)
  13. }

方法2

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func main() {
  7. now := time.Now()
  8. t, _ := time.ParseInLocation("2006-01-02", now.Format("2006-01-02"), time.Local)
  9. timestamp := t.Unix()
  10. fmt.Println(timestamp)
  11. }
  12. /* time.Local本地时区 var Local *Location = &localLoc 以及UTC时区 var UTC *Location = &utcLoc 还可以替换成指定时区 //func LoadLocation(name string) (*Location, error) loc, _ := time.LoadLocation("Europe/Berlin") If the name is "" or "UTC", LoadLocation returns UTC. If the name is "Local", LoadLocation returns Local. */

参考

官方文档:The Go Programming Language-Package time

发表评论

表情:
评论列表 (有 0 条评论,488人围观)

还没有评论,来说两句吧...

相关阅读