# Time Modules:
### Author:品茶
> 时间是一种类型,是支持与时间比较,常见的方式有
> datetime 2006-01-02 15:04:05
> date 2006-01-02
> timestamp 1500373681
GO中时间模块也支持在一定时间内执行任务,即类定时任务的概念。但专业的还是用其它模块。
~~~
package main
import (
"fmt"
"log"
"time"
)
func main() {
t := time.Now()
layout := "2006-01-02 15:04:05"
// time to date(string) layout need "2006-01-02 15:04:05"
date := t.Format("2006-01-02")
// time to datetime(string)
dateTime := t.Format(layout)
// string to Time
tn, err := time.Parse(layout, dateTime)
if err != nil {
log.Fatal(err)
}
// timestamp
ts := time.Now().Unix()
// timestamp to string(date or datetime)
tts := time.Unix(ts, 0)
tts.Format(layout)
// string to timestamp
st, err := time.Parse(layout, dateTime)
if err != nil {
log.Fatal(err)
}
// 增加时间 减少时间
// add month 单位
// Nanosecond Duration = 1
// Microsecond = 1000 * Nanosecond
// Millisecond = 1000 * Microsecond
// Second = 1000 * Millisecond
// Minute = 60 * Second
// Hour = 60 * Minute
at := t.Add(time.Hour * 2)
//判断两个时间之前或之后 返回bool t在at之后
fmt.Println("time: t(now) > time: at(now+2h)", t.After(at))
fmt.Println("time: t(now) < time: at(now+2h)", t.Before(at))
//获取时间的小时、分、秒 年、月、日、星期
fmt.Println(t.Hour(), t.Minute(), t.Second(), t.Year(), t.Month(), t.Day(),
t.Weekday())
//获取时间的字符串表示
fmt.Println(t.String())
fmt.Println(ts)
fmt.Println(tn)
fmt.Println(date)
fmt.Println(dateTime)
fmt.Println(tts)
fmt.Println(st)
fmt.Println(at)
}
~~~
# Output:
~~~
//time: t(now) > time: at(now+2h) false
//time: t(now) < time: at(now+2h) true
//18 28 1 2017 July 18 Tuesday
//2017-07-18 18:28:01.866748627 +0800 CST
//1500373681
//2017-07-18 18:28:01 +0000 UTC
//2017-07-18
//2017-07-18 18:28:01
//2017-07-18 18:28:01 +0800 CST
//2017-07-18 18:28:01 +0000 UTC
//2017-07-18 20:28:01.866748627 +0800 CST
~~~