Go语言时间包time中的可用函数和方法 定义 总结和使用示例

Go语言时间包time中的可用函数和方法

Constants 时间常量 这个就是常用的时间格式布局的常量定义

这个在我们对时间进行解析或者转换为字符串是非常重要, 如果是下面的这些类型之一的可用直接 time.XXX 就可使用, 如常见的标准时间格式 年月日时分秒(2006-01-02 15:04:05) 我们可以直接 time.DateTime 即可。

go 复制代码
const (
	Layout      = "01/02 03:04:05PM '06 -0700" // The reference time, in numerical order.
	ANSIC       = "Mon Jan _2 15:04:05 2006"
	UnixDate    = "Mon Jan _2 15:04:05 MST 2006"
	RubyDate    = "Mon Jan 02 15:04:05 -0700 2006"
	RFC822      = "02 Jan 06 15:04 MST"
	RFC822Z     = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone
	RFC850      = "Monday, 02-Jan-06 15:04:05 MST"
	RFC1123     = "Mon, 02 Jan 2006 15:04:05 MST"
	RFC1123Z    = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone
	RFC3339     = "2006-01-02T15:04:05Z07:00"
	RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
	Kitchen     = "3:04PM"
	// Handy time stamps.
	Stamp      = "Jan _2 15:04:05"
	StampMilli = "Jan _2 15:04:05.000"
	StampMicro = "Jan _2 15:04:05.000000"
	StampNano  = "Jan _2 15:04:05.000000000"
	DateTime   = "2006-01-02 15:04:05"
	DateOnly   = "2006-01-02"
	TimeOnly   = "15:04:05"
)

这个后面就是time包里面提供的函数 , 类型定义和方法定义了

这些函数和方法使用也很简单, 看函数就大概知道是用来干什么的。 不清楚的还可以查看相关的使用示例,地址 https://pkg.go.dev/time@go1.22.4#pkg-examples

  • func After(d Duration) <-chan Time
  • func Sleep(d Duration) 休眠 函数,这个不用说了,非常常用,用于让程序休眠指定的时间
  • 如:让代码休眠1秒钟:
go 复制代码
time.Sleep(time.Duration(time.Second * 1))
// 这里的 time.Second 是一个常量 他其实就是一个数字,其他几个相关的常量定义如下
// const (
// 	Nanosecond  Duration = 1
// 	Microsecond          = 1000 * Nanosecond
// 	Millisecond          = 1000 * Microsecond
// 	Second               = 1000 * Millisecond
// 	Minute               = 60 * Second
// 	Hour                 = 60 * Minute
// )

这里有一点需要注意, 如果我么传递的时间数字是一个变量,则需要使用 time.Duration(变量名)来转换一下后才可以做运算。

如:

go 复制代码
	seconds := 10
	fmt.Print(time.Duration(seconds)*time.Second) // prints 10s
  • func Tick(d Duration) <-chan Time

type Duration 持续时间类型, 这个也是一个很常用的类型

    • func ParseDuration(s string) (Duration, error)
    • func Since(t Time) Duration
    • func Until(t Time) Duration
    • func (d Duration) Abs() Duration
    • func (d Duration) Hours() float64
    • func (d Duration) Microseconds() int64
    • func (d Duration) Milliseconds() int64
    • func (d Duration) Minutes() float64
    • func (d Duration) Nanoseconds() int64
    • func (d Duration) Round(m Duration) Duration
    • func (d Duration) Seconds() float64
    • func (d Duration) String() string
    • func (d Duration) Truncate(m Duration) Duration
  • type Location 本地时间类型
    • func FixedZone(name string, offset int) *Location
    • func LoadLocation(name string) (*Location, error)
    • func LoadLocationFromTZData(name string, data ]byte) (*Location, error)
    • func (l *Location) String() string
  • type Month
    • func (m Month) String() string
  • type ParseError
    • func (e *ParseError) Error() string

type Ticker 断续器类型

    • ** func NewTicker(d Duration) *Ticker ** 这个也很常用,用于创建一个带通道的每隔一定时间就输出的断续器
      使用示例:

      go 复制代码
      package main
      
      import (
      	"fmt"
      	"time"
      )
      
      func main() {
      	ticker := time.NewTicker(time.Second)
      	defer ticker.Stop()
      	done := make(chan bool)
      	go func() {
      		time.Sleep(10 * time.Second)
      		done <- true
      	}()
      	for {
      		select {
      		case <-done:
      			fmt.Println("Done!")
      			return
      		case t := <-ticker.C:
      			fmt.Println("Current time: ", t)
      		}
      	}
      }

``

    • func (t *Ticker) Reset(d Duration)
    • func (t *Ticker) Stop()

type Time 时间对象类型

    • func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time
    • func Now() Time 这个函数应该是使用最为频繁的一个了,获取当前时间对象
    • func Parse(layout, value string) (Time, error) 这个是时间解析函数 用于将字符串转换为时间对象。
    • func ParseInLocation(layout, value string, loc *Location) (Time, error)
    • func Unix(sec int64, nsec int64) Time
    • func UnixMicro(usec int64) Time
    • func UnixMilli(msec int64) Time
    • 以下这些都是时间对象的方法,很简单,看名字就知道是干什么用的 这里就不做过多解释了。
    • 有一点提醒大家注意的是,这里的时间对象 Time是标准类型不是*指针类型哦!
    • func (t Time) Add(d Duration) Time
    • func (t Time) AddDate(years int, months int, days int) Time
    • func (t Time) After(u Time) bool
    • func (t Time) AppendFormat(b ]byte, layout string) ]byte
    • func (t Time) Before(u Time) bool
    • func (t Time) Clock() (hour, min, sec int)
    • func (t Time) Compare(u Time) int
    • func (t Time) Date() (year int, month Month, day int)
    • func (t Time) Day() int
    • func (t Time) Equal(u Time) bool
    • func (t Time) Format(layout string) string 时间对象转换为字符串方法
    • func (t Time) GoString() string
    • func (t *Time) GobDecode(data ]byte) error
    • func (t Time) GobEncode() (]byte, error)
    • func (t Time) Hour() int
    • func (t Time) ISOWeek() (year, week int)
    • func (t Time) In(loc *Location) Time
    • func (t Time) IsDST() bool
    • func (t Time) IsZero() bool 这个方法是专门用来判断Time对象是否为空的,注意了,Time对象的零值很特别!!!
    • func (t Time) Local() Time
    • func (t Time) Location() *Location
    • func (t Time) MarshalBinary() (]byte, error)
    • func (t Time) MarshalJSON() (]byte, error)
    • func (t Time) MarshalText() (]byte, error)
    • func (t Time) Minute() int
    • func (t Time) Month() Month
    • func (t Time) Nanosecond() int
    • func (t Time) Round(d Duration) Time
    • func (t Time) Second() int
    • func (t Time) String() string
    • func (t Time) Sub(u Time) Duration
    • func (t Time) Truncate(d Duration) Time
    • func (t Time) UTC() Time
    • func (t Time) Unix() int64
    • func (t Time) UnixMicro() int64
    • func (t Time) UnixMilli() int64
    • func (t Time) UnixNano() int64
    • func (t *Time) UnmarshalBinary(data ]byte) error
    • func (t *Time) UnmarshalJSON(data ]byte) error
    • func (t *Time) UnmarshalText(data ]byte) error
    • func (t Time) Weekday() Weekday
    • func (t Time) Year() int
    • func (t Time) YearDay() int
    • func (t Time) Zone() (name string, offset int)
    • func (t Time) ZoneBounds() (start, end Time)

type Timer 定时器类型

    • func AfterFunc(d Duration, f func()) *Timer
    • *func NewTimer(d Duration) Timer 新建一个在指定的时间后执行一次的定时器函数, 注意这个只会在你指定的时间执行一次, 而 NewTicker创建的 Ticker 则是在你指定的时间间隔上不停地重复执行
    • func (t *Timer) Reset(d Duration) bool
    • func (t *Timer) Stop() bool
  • type Weekday

    • func (d Weekday) String() string
相关推荐
Scott9999HH5 小时前
【IIoT流量实战】蒸汽管道阀门全关却仍有流量?用 Python 实现涡街信号 FFT 频谱分析与温压全补偿积算网关,深度拆解靠谱的涡街流量计厂家硬核技术标准
开发语言·python
码智社6 小时前
AES加密原理详解及Java实现加解密实战
java·开发语言
AI云海6 小时前
python 列表、元组、集合和字典
开发语言·python
萧瑟余晖7 小时前
JDK 26 新特性详解
java·开发语言
马优晨8 小时前
Freemarker 完整讲解(后端 Java 模板引擎)
java·开发语言·freemarker·freemarker 完整讲解·freemarker模板引擎
人邮异步社区10 小时前
怎么把C语言学到精通?
c语言·开发语言
心平气和量大福大10 小时前
C#-WPF-控件-TextBox 数据绑定
开发语言·c#·wpf
ttwuai11 小时前
Cursor 生成 CRUD 后,Go 后台接口别只测 200:JWT、RBAC 和 tenant_id 怎么验
开发语言·后端·golang
এ慕ོ冬℘゜11 小时前
前端基础:什么是时间戳?JS获取时间戳三种方法与实战用途
开发语言·前端·javascript
执明wa11 小时前
LayoutInflater详解: XML是如何变成View的?
android·xml·开发语言·android studio