Golang

关注公众号 jb51net

关闭
首页 > 脚本专栏 > Golang > Go语言DateTime

Go语言中DateTime的用法介绍

作者:奋斗的大橙子

这篇文章介绍了Go语言中DateTime的用法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

一、基本使用

①从属于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类型中的

④常用 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

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对脚本之家的支持。如果你想了解更多相关内容请查看下面相关链接

您可能感兴趣的文章:
阅读全文