Go语言中DateTime的用法介绍
作者:奋斗的大橙子 时间:2024-04-27 15:31:55
一、基本使用
①从属于time这个包
②一般使用都是使用
time.Time 这个类型表示时间 ,time包中还有一些常量,源码如下
// Common durations. There is no definition for units of Day or larger
// to avoid confusion across daylight savings time zone transitions.
//
// To count the number of units in a Duration, divide:
// second := time.Second
// fmt.Print(int64(second/time.Millisecond)) // prints 1000
//
// To convert an integer number of units to a Duration, multiply:
// seconds := 10
// fmt.Print(time.Duration(seconds)*time.Second) // prints 10s
//<br data-filtered="filtered">
const (
Nanosecond Duration = 1
Microsecond = 1000 * Nanosecond
Millisecond = 1000 * Microsecond
Second = 1000 * Millisecond
Minute = 60 * Second
Hour = 60 * Minute
)
③ time.Now() 获取当前的时间,返回的是Time类型
Time类型中的
Year() 获取当前的年份
Month() 获取当前的月份
Day() 获取当前的日期
Hour() 获取当前小时
Minute() 获取当前分钟
Second() 获取当前秒
④常用 Unix() 方法获取时间戳信息
⑤通过AddDate()方法增加指定日期,Add方法增加指定时间
举个例子:
①打印时间基础信息
func DateTimeBasic() time.Time{
now:=time.Now()
fmt.Printf("%v\n",now)
year:=now.Year()
month:=now.Month()
day:=now.Day()
hour:=now.Hour()
minute:=now.Minute()
send:=now.Second()
fmt.Printf("%02d/%02d/%02d %02d:%02d:%02d\n",year,month,day,hour,minute,send)
return now
}
② 时间和时间戳直接的转换 第一个函数输入时间返回时间戳,第二个函数输入时间戳返回时间
func GetDateTimeStamp(datetime time.Time) int64{
now:=datetime.Unix()
fmt.Printf("TimeStamp: %v\n",now)
return now
}
func GetDateTime(timeStamp int64){
now:=time.Unix(timeStamp,0)
fmt.Printf("DateTime: %v\n",now)
}
③增加时间
func AddDay(src time.Time) time.Time{
//添加一天两小时
src = src.AddDate(0,0,1).Add(time.Hour * 2)
return src
}
④测试一下
package main
import "DateTimeDemo"
func main(){
dateTime:=DateTimeDemo.DateTimeBasic()
calcDateTime := DateTimeDemo.AddDay(dateTime)
timeStamp:=DateTimeDemo.GetDateTimeStamp(calcDateTime)
DateTimeDemo.GetDateTime(timeStamp)
}
⑤输出
2019-02-26 16:51:59.7509972 +0800 CST m=+0.010553801
2019/02/26 16:51:59
TimeStamp: 1551264719
DateTime: 2019-02-27 18:51:59 +0800 CST
二、简单定时器
利用time中Tick()方法
func SimpleTicker(){
//间隔两秒,会像Channel中写入一个数据
ticker := time.Tick(time.Second * 2)
for i := range ticker{
fmt.Printf("%v\n",i)
simpleTask()
}
}
func simpleTask(){
fmt.Println("Task Start")
}
执行结果:
2019-02-26 16:54:43.7828451 +0800 CST m=+2.077803401
Task Start
2019-02-26 16:54:45.7831559 +0800 CST m=+4.078114201
Task Start
2019-02-26 16:54:47.7831744 +0800 CST m=+6.078132701
Task Start
2019-02-26 16:54:49.7833155 +0800 CST m=+8.078273801
Task Start
2019-02-26 16:54:51.782682 +0800 CST m=+10.077640301
Task Start
来源:https://www.cnblogs.com/dcz2015/p/10438479.html