Golang之时间、日期类型

孤身只影的一直小地鼠,艰难的走在路上

package main

import (
    "fmt"
    "time"
)

//获取时间的格式
func testTime() {
    now := time.Now()
    fmt.Printf("current time:%v\n", now)

    year := now.Year()
    month := now.Month()
    day := now.Day()
    hour := now.Hour()
    minute := now.Minute()
    second := now.Second()
    // %02d表示不够2位的话,就补0
    fmt.Printf("%02d-%02d-%02d %02d:%02d:%02d\n ", year, month, day, hour, minute, second)
}

//获取时间戳
func testTimestamp(timestamp int64) {
    timeObj := time.Unix(timestamp, 0)
    year := timeObj.Year()
    month := timeObj.Month()
    day := timeObj.Day()
    hour := timeObj.Hour()
    minute := timeObj.Minute()
    second := timeObj.Second()

    fmt.Printf("current timestamp:%d\n", timestamp)
    fmt.Printf("%02d-%02d-%02d %02d:%02d:%02d\n", year, month, day, hour, minute, second)
}

func processTask() {
    fmt.Printf("do task\n")
}

//定时器
func testTicker() {
    ticker := time.Tick(1 * time.Second)
    for i := range ticker {
        fmt.Printf("%v\n", i)
        processTask()
    }
}

//time.Duration用来表示纳秒
func testConst() {
    //一些常量
    fmt.Printf("nano second:%d\n", time.Nanosecond)
    fmt.Printf("micro second:%d\n", time.Microsecond)
    fmt.Printf("mili second:%d\n", time.Millisecond)
    fmt.Printf("second:%d\n", time.Second)
}
//时间格式化
func testFormat() {
    now := time.Now()
    timeStr := now.Format("2006-01-02 15:04:05")
    fmt.Printf("time:%s\n", timeStr)
}

func main() {
    //testTime()
    //timestamp := time.Now().Unix()
    //testTimestamp(timestamp)
    //testTicker()
    //testConst()
    testFormat()
}

 

posted @ 2018-02-09 15:06  py鱼  阅读(2842)  评论(0编辑  收藏  举报
点我回主页