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()
}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

扫码关注云+社区

领取腾讯云代金券