1. 程式人生 > >golang時間字串和時間戳轉換

golang時間字串和時間戳轉換

1. 獲取當前時間字串和時間戳

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now().UTC()
    // 顯示時間格式: UnixDate = "Mon Jan _2 15:04:05 MST 2006"
    fmt.Printf("%s\n", now.Format(time.UnixDate))
    // 顯示時間戳
    fmt.Printf("%ld\n", now.Unix())
    // 顯示時分:Kitchen = "3:04PM"
    fmt.Printf("%s\n"
, now.Format("3:04PM")) }

更多時間格式

const (
        ANSIC       = "Mon Jan _2 15:04:05 2006"
        UnixDate    = "Mon Jan _2 15:04:05 MST 2006"
        RubyDate    = "Mon Jan 02 15:04:05 -0700 2006"
        RFC822      = "02 Jan 06 15:04 MST"
        RFC822Z     = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone
        RFC850      = "Monday, 02-Jan-06 15:04:05 MST"
RFC1123 = "Mon, 02 Jan 2006 15:04:05 MST" RFC1123Z = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone RFC3339 = "2006-01-02T15:04:05Z07:00" RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00" Kitchen = "3:04PM" // Handy time stamps. Stamp = "Jan _2 15:04:05"
StampMilli = "Jan _2 15:04:05.000" StampMicro = "Jan _2 15:04:05.000000" StampNano = "Jan _2 15:04:05.000000000" )

2. 時間字串解析成時間格式

package main

import (
    "fmt"
    "time"
)

func main() {
    timeStr := "2018-01-01"
    fmt.Println("timeStr:", timeStr)
    t, _ := time.Parse("2006-01-02", timeStr)
    fmt.Println(t.Format(time.UnixDate))
}

3. 獲取當天零點時間戳

方法1

package main

import (
    "fmt"
    "time"
)

func main() {
    timeStr := time.Now().Format("2006-01-02")
    t, _ := time.Parse("2006-01-02", timeStr)
    fmt.Println(t.Format(time.UnixDate))
    //Unix返回早八點的時間戳,減去8個小時
    timestamp := t.UTC().Unix() - 8*3600
    fmt.Println("timestamp:", timestamp)
}

方法2

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    t, _ := time.ParseInLocation("2006-01-02", now.Format("2006-01-02"), time.Local)
    timestamp := t.Unix()
    fmt.Println(timestamp)
}
/*
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.
*/

參考