Go convert string to time

本文主要以代碼實例的形式,說明了Golang語言中,time對象和string對象之間的轉換。

源碼

package main

import (
    "fmt"
    "reflect"
    "time"
)

func main() {

    fmt.Println("----------------當前時間/時間戳/字符串----------------")
    t := time.Now()
    timestamp := t.Unix()
    fmt.Println("當前本時區時間:", t)
    fmt.Println("當前本時區時間時間戳:", timestamp)

    t = time.Now().UTC()
    timestamp = t.Unix()
    fmt.Println("當前零時區時間:", t)
    fmt.Println("當前零時區時間時間戳:", timestamp)
    fmt.Println("當前時間對應字符串:", t.Format("2006-01-02 15:04:05"))

    fmt.Println("")

    fmt.Println("------指定字符串後,字符串和時間戳之間的相互轉換------")
    // 字符串-->時間戳
    // 方法一
    the_time := time.Date(2017, 7, 7, 9, 0, 0, 0, time.Local)
    unix_time := the_time.Unix()
    fmt.Println("方法一 時間戳:", unix_time, reflect.TypeOf(unix_time))

    // 方法二
    the_time, err := time.ParseInLocation("2006-01-02 15:04:05", "2017-07-07 09:00:00", time.Local)
    if err == nil {
        unix_time = the_time.Unix()
        fmt.Println("方法二 時間戳:", unix_time, reflect.TypeOf(unix_time))
    }

    // 時間戳--> 字符串
    res := time.Unix(unix_time, 0).Format("2006-01-02 15:04:05")
    fmt.Println("時間戳對應字符串:", res, reflect.TypeOf(res))
}

運行結果

----------------當前時間/時間戳/字符串----------------
當前本時區時間: 2017-07-07 09:22:13.4999002 +0800 CST
當前本時區時間時間戳: 1499390533
當前零時區時間: 2017-07-07 01:22:13.5219002 +0000 UTC
當前零時區時間時間戳: 1499390533
當前時間對應字符串: 2017-07-07 01:22:13

------指定字符串後,字符串和時間戳之間的相互轉換------
方法一 時間戳: 1499389200 int64
方法二 時間戳: 1499389200 int64
時間戳對應字符串: 2017-07-07 09:00:00 string

參考

  1. golang 常用時間處理示例
  2. golang/pkg/time
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章