Time类型
Now方法表示现在时间。
func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time
返回现在的时间,
func (t Time) Unix() int64将时间转换为unix时间戳,因为duration的限制,所以应该只能计算从1970年开始的250年左右
func Unix(sec int64, nsec int64) Time将时间戳转化为Time对象,看上去相似,只不过这不是time类型的方法
将各种格式的string格式的时间转换为Time对象用Parse方法
format.go里定义了一些格式
const (
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"
)
当然也可以自己定义
const longForm = "Jan 2, 2006 at 3:04pm (MST)"
t, _ := time.Parse(longForm, "Feb 3, 2013 at 7:54pm (PST)")
time.format用的就是2016-01-02 15:04:05这个时间,随意的自己定义会出现不正确的情况,可以去goplayground上跑一下,比如
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println(time.Now().Format("2004-10-06"))
}
10000-110-09
另一个Duration类型,表示时间差,通常用来执行定时任务或者计算到期时间等
看源代码,计数从ns开始所以264/103/103/103/60/60/24/365 大约还剩2^9次方的数量级,所以前后推250年左右,通常已经可以满足需求
type Duration int64
const (
minDuration Duration = -1 << 63
maxDuration Duration = 1<<63 - 1
)
const (
Nanosecond Duration = 1
Microsecond = 1000 * Nanosecond
Millisecond = 1000 * Microsecond
Second = 1000 * Millisecond
Minute = 60 * Second
Hour = 60 * Minute
)
ParseDuration(s string) (Duration, error) 把Duration String转为Duration对象
对应有func (Duration) Hours,func (Duration) Minutes, func (Duration) Seconds, func (Duration) Nanoseconds取小时数等
关于Duration用法的一个点
如上看到 type Duration int64这一定义
因此我们可以使用常量*time.Second的方式来定义时长,比如700*time.Millisecond
但是不能使用变量 a := 700 a*time.Milliscond
这种用法,因为不同类型的不能相乘。建议使用time.Duration(700)*time.Milliscond
这种用法