time时间模块
362字约1分钟
2025-02-03
package main
import (
"fmt"
"time"
)
func main() {
// 1. 导入time包
// 导入time包,以便使用其中的函数和类型。
// 2. 获取当前时间
// 获取当前时间,并将其格式化为字符串。
now := time.Now()
fmt.Println("当前时间:", now.Format("2006-01-02 15:04:05"))
fmt.Println(now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second())
newtime := fmt.Sprintf("%d-%02d-%02dT%02d:%02d:%02d-00:00\n",
now.Year(), now.Month(), now.Day(),
now.Hour(), now.Minute(), now.Second())
fmt.Println(newtime)
// 3. 格式化时间
// 格式化时间,将时间戳转换为指定格式的字符串。
timestamp := now.UnixNano() / int64(time.Millisecond)
fmt.Println("时间戳:", timestamp)
seconds := timestamp / 1000
nanoseconds := (timestamp % 1000) * 1e6
// 根据秒级时间戳和纳秒部分创建时间对象
t := time.Unix(seconds, nanoseconds)
// 格式化时间对象为字符串
formattedTime := t.Format("2006-01-02 15:04:05")
fmt.Println("Formatted time:", formattedTime)
// 4. 计算时间差
// 计算两个时间之间的差值,并将其转换为指定格式的字符串。
start := time.Now()
time.Sleep(time.Second)
duration := time.Since(start)
fmt.Println("时间差:", duration.Hours(), "小时", duration.Minutes(), "分钟", duration.Seconds(), "秒")
fmt.Println("时间差:", duration.String())
// 5. 计算指定日期和时间
// 计算指定日期和时间,并将其格式化为字符串。
specifiedTime := time.Date(2021, 1, 1, 12, 0, 0, 0, time.UTC)
fmt.Println("指定时间:", specifiedTime.Format("2006-01-02 15:04:05"))
// 6. 计算时间范围
// 计算两个时间之间的差值,并将其转换为指定格式的字符串。
timeRange := now.Sub(specifiedTime)
fmt.Println("时间范围:", timeRange.Hours(), "小时", timeRange.Minutes(), "分钟", timeRange.Seconds(), "秒")
}