Go - 獲取當前時間 時間格式的轉換 秒、毫秒、納秒時間戳輸出


1. Go時間格式的轉換

 

package main

import (
    "fmt"
    "time"
)

func main() {

    t := time.Now()   //2019-07-31 13:55:21.3410012 +0800 CST m=+0.006015601
    fmt.Println(t.Format("20060102150405"))

    //當前時間戳
    t1 := time.Now().Unix()  //1564552562
    fmt.Println(t1)
    //時間戳轉化為具體時間
    fmt.Println(time.Unix(t1, 0).String())

    //基本格式化的時間表示
    fmt.Println(time.Now().String()) //2019-07-31 13:56:35.7766729 +0800 CST m=+0.005042501

    fmt.Println(time.Now().Format("2006-01-02"))  //2019-07-31
    fmt.Println(time.Now().Format("2006-01-02 15:04:05"))  //2019-07-31 13:57:52

    //獲取第幾周
    _, week := time.Now().ISOWeek()  
    //獲取年、月、日
    year, month, day := rwTools.DateYmdInts() 
}

// 時間戳轉年月日 時分秒
func DateFormat(timestamp int) string {
    tm := time.Unix(int64(timestamp), 0)
    return tm.Format("2006-01-02 15:04")
}

//時間戳轉年月日
func DateFormatYmd(timestamp int) string {
    tm := time.Unix(int64(timestamp), 0)
    return tm.Format("2006-01-02")
}

//獲取當前年月
func DateYmFormat() string {
    tm := time.Now()
    return tm.Format("2006-01")
}

//獲取年月日時分秒(字符串類型)
func DateNowFormatStr() string {
    tm := time.Now()
    return tm.Format("2006-01-02 15:04:05")
}

//時間戳
func DateUnix() int {
    t := time.Now().Local().Unix()
    return int(t)
}

//獲取年月日時分秒(time類型)
func DateNowFormat() time.Time {
    tm := time.Now()
    return tm
}

//獲取第幾周
func DateWeek() int {
    _, week := time.Now().ISOWeek()
    return week
}

//獲取年、月、日
func DateYMD() (int,int, int) {
    year, month, day := DateYmdInts()
    return year,month,day
}

// 獲取年月日
func DateYmdFormat() string {
    tm := time.Now()
    return tm.Format("2006-01-02")
}

// 獲取日期的年月日
func DateYmdInts() (int, int, int) {
    timeNow := time.Now()
    year, month, day := timeNow.Date()
    return year, int(month), day
}

 

2.golang的time包:秒、毫秒、納秒時間戳輸出

時間戳
10位數的是以 秒 為單位;
13位數的是以 毫秒 為單位;
19位數的是以 納秒 為單位;

package main

import (
    "time"
    "fmt"
)

func main() {
    fmt.Printf("時間戳(秒):%v;\n", time.Now().Unix())
    fmt.Printf("時間戳(納秒):%v;\n",time.Now().UnixNano())
    fmt.Printf("時間戳(毫秒):%v;\n",time.Now().UnixNano() / 1e6)
    fmt.Printf("時間戳(納秒轉換為秒):%v;\n",time.Now().UnixNano() / 1e9)
}

"""
輸出結果
時間戳(秒):1530027865;
時間戳(納秒):1530027865231834600;
時間戳(毫秒):1530027865231;
時間戳(納秒轉換為秒):1530027865;
"""

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM