Golang之时间、日期类型

本文介绍了一段使用Go语言处理时间的代码示例,包括获取当前时间、格式化时间、使用时间戳以及设置定时任务等常见操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

 

转载于:https://www.cnblogs.com/pyyu/p/8435535.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值