TOC

Golang 时间处理

time.Now()              // time.Time

// type Month int
// const (
//  January Month = 1 + iota
//  February
//  March
//  April
//  May
//  June
//  July
//  August
//  September
//  October
//  November
//  December
// )
// var Local *Location = &localLoc
func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time // 组装 Time

// Time -> 时间戳
time.Now().Unix()       // int64
time.Now().UnixMilli()  // int64 毫秒
time.Now().UnixMicro()  // int64 微秒
time.Now().UnixNano()   // int64 纳秒

func Unix(sec int64, nsec int64) Time   // 时间戳 -> Time

time.Now().Format("2006-01-02 15:04:05")    // Time -> timestr
time.Parse("2006-01-02 15:04:05", timestr)  // timestr -> Time

间隔计算

func (t Time) Truncate(d Duration) Time
func (t Time) Round(d Duration) Time

func (d Duration) Truncate(m Duration) Duration
func (d Duration) Round(m Duration) Duration

func (t Time) Add(d Duration) Time  // Time 相加
func (t Time) Sub(u Time) Duration  // Time 相减

func Since(t Time) Duration         // Now - t
func Until(t Time) Duration         // t - Now

time.Now().Truncate(时间)
package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println("Hello, 世界")
    now := time.Date(2021, 5, 21, 15, 46, 47, 0, time.Local)
    fmt.Println(now)
    // d := time.Hour
    d := time.Duration(3000_000_000_000)
    fmt.Println(now.Truncate(d))
    fmt.Println(now.Round(d))
}
// 2021-05-21 15:46:47 +0000 UTC
// 2021-05-21 15:00:00 +0000 UTC
// 2021-05-21 15:50:00 +0000 UTC