Golang 时间互转

更新于 2022-10-29 10:30 40
专栏: Golang 标签: Go

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func main() {
  7. Str2Time:=Str2Time("2017-09-12 12:03:40")
  8. fmt.Println(Str2Time)
  9. Str2Stamp:=Str2Stamp("2017-09-12 12:03:40")
  10. fmt.Println(Str2Stamp)
  11. Time2Str:=Time2Str()
  12. fmt.Println(Time2Str)
  13. GetStamp:=Time2Stamp()
  14. fmt.Println(GetStamp)
  15. Stamp2Str:=Stamp2Str(1505189020000)
  16. fmt.Println(Stamp2Str)
  17. Stamp2Time:=Stamp2Time(1505188820000)
  18. fmt.Println(Stamp2Time)
  19. }
  20. /**字符串->时间对象*/
  21. func Str2Time(formatTimeStr string) time.Time{
  22. timeLayout := "2006-01-02 15:04:05"
  23. loc, _ := time.LoadLocation("Local")
  24. theTime, _ := time.ParseInLocation(timeLayout, formatTimeStr, loc) //使用模板在对应时区转化为time.time类型
  25. return theTime
  26. }
  27. /**字符串->时间戳*/
  28. func Str2Stamp(formatTimeStr string) int64 {
  29. timeStruct:=Str2Time(formatTimeStr)
  30. millisecond:=timeStruct.UnixNano()/1e6
  31. return millisecond
  32. }
  33. /**时间对象->字符串*/
  34. func Time2Str() string {
  35. const shortForm = "2006-01-01 15:04:05"
  36. t := time.Now()
  37. temp := time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), time.Local)
  38. str := temp.Format(shortForm)
  39. return str
  40. }
  41. /*时间对象->时间戳*/
  42. func Time2Stamp()int64{
  43. t:=time.Now()
  44. millisecond:=t.UnixNano()/1e6
  45. return millisecond
  46. }
  47. /*时间戳->字符串*/
  48. func Stamp2Str(stamp int64) string{
  49. timeLayout := "2006-01-02 15:04:05"
  50. str:=time.Unix(stamp/1000,0).Format(timeLayout)
  51. return str
  52. }
  53. /*时间戳->时间对象*/
  54. func Stamp2Time(stamp int64)time.Time{
  55. stampStr:=Stamp2Str(stamp)
  56. timer:=Str2Time(stampStr)
  57. return timer
  58. }

BLOG

搜索文章