golang使⽤time包获取时间戳与⽇期格式化操作Time包定义的类型
Time: 时间类型, 包含了秒和纳秒以及 Location
Month: type Month int ⽉份.
定义了⼗⼆个⽉的常量
const (
January Month = 1 + iota
February
March
April
May
June
July
August
September
October
November
December
)
Weekday 类型: type Weekday int 周
定义了⼀周的七天
const (
Sunday Weekday = iota
Monday
Tuesday
Wednesday
unix时间戳转换日期格式Thursday
Friday
Saturday
)
Duration: type Duration int64 持续时间.
定义了以下持续时间类型.
多⽤于时间的加减需要传⼊Duration做为参数的时候.
可以直接传⼊ time.Second
const (
Nanosecond Duration = 1
Microsecond  = 1000 * Nanosecond
Millisecond  = 1000 * Microsecond
Second    = 1000 * Millisecond
Minute    = 60 * Second
Hour    = 60 * Minute
)
Location
在time包⾥有两个时区变量:
time.UTC utc时间
time.Local 本地时间
时间格式化
时间格式Time:
fmt.Println(time.Now())
// 输出: 2019-04-30 14:41:59.661602 +0800 CST m=+0.000225294
fmt.Println(time.Now().String())
// 输出: 2019-04-30 14:41:59.661826 +0800 CST m=+0.000448434
获取当前时间戳:
// 获取当前unix时间戳(秒)
fmt.Println(time.Now().Unix()) // 输出: 1556615702
// 获取当前unix时间戳(毫秒)
fmt.Println(time.Now().UnixNano() / 1e6) // 输出: 1556615702009
// 获取当前unix时间戳(纳秒)
fmt.Println(time.Now().UnixNano()) // 输出: 1556615702009257000
字符串转化成时间戳:
x := "2018-12-27 18:44:55"
p, _ := time.Parse("2006-01-02 15:04:05", x)
fmt.Println( p.Unix() ) // 输出: 1545936295
将当前时间转成年⽉⽇时分秒格式:
t = time.Now()
fmt.Println(t.Format("2006-01-02"))  // 输出: 2019-04-30
fmt.Println(t.Format("2006-01-02 15:04:05")) // 输出: 2019-04-30 14:43:26
fmt.Println(t.Format("2006-01-02 00:00:00")) // 输出: 2019-04-30 00:00:00
fmt.Println(t.Format("2006/01/02 15:04")) // 输出: 2019-04-30 14:43
fmt.Println(t.Format("2006/Jan/02 15:04")) // 输出: 2019/Apr/30 17:28
// 指定时间
t2 := time.Date(2019, time.November, 28, 11, 35, 46, 0, time.UTC)
// 返回 Time 类型
fmt.Printf("=>⽇期格式: %s\n", t2.Format("06/01/02 15:04:05"))
// 输出: =>⽇期格式: 19/11/28 11:35:46
注意:
⽐如在PHP中,我们使⽤ date(‘Y-m-d H:i:s', time()) 可以输出时间 “2019-04-30 14:43:26”,⽐如Java⾥的 “new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”)”。
但是在Go语⾔中,“Y-m-d H:i:s”、 “yyyy-MM-dd HH:mm:ss”为特定的数字 “2006-01-02 15:04:05”是Go语⾔的创建时间,且必须为这⼏个准确的数字。
使⽤ time.Now().Date() 获取年⽉⽇:
// Date()返回三个参数: 年⽉⽇
year1, month1, day1 := time.Now().Date()
fmt.Printf("year: %v, type: %T \n", year1, year1)
// 输出: year: 2019, type: int
fmt.Printf("month: %v, type: %T \n", month1, month1)
// 输出: month: April, type: time.Month
fmt.Printf("day: %v, type: %T \n", day1, day1)
// 输出: day: 30, type: int
补充:golang的time.Format的坑
golang的time.Format设计的和其他语⾔都不⼀样, 其他语⾔总是使⽤⼀些格式化字符进⾏标⽰, ⽽golang呢, 查了⽹上⼀些坑例⼦⾃⼰查了下golang的源码, 发现以下代码
// String returns the time formatted using the format string
// "2006-01-02 15:04:05.999999999 -0700 MST"
func (t Time) String() string {
return t.Format("2006-01-02 15:04:05.999999999 -0700 MST")
}
尝试将2006-01-02 15:04:05写⼊到⾃⼰的例⼦中
func nowTime() string {
return time.Now().Format("2006-01-02 15:04:05")
}
结果返回正确. 询问了下, 据说这个⽇期是golang诞⽣的⽇⼦… 咋那么⾃恋呢…
以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。如有错误或未考虑完全的地⽅,望不吝赐教。