文章目录
  1. 1. 1. 获取当前时间
  2. 2. 2. 日期时间格式化
  3. 3. 3. 字符串日期时间转time
  4. 4. 4. 获取年/月/周/日/时/分/秒

在go语言的标准库里,可以通过time来处理日期和时间。我们需要引用标准库

1
import "time"

1. 获取当前时间

1
2
3
4
5
6
7
now := time.Now()
fmt.Println(now)
// 当前时间戳,1970年1月1日到现在的秒数
fmt.Println(" 秒", now.Unix())
fmt.Println("豪秒", now.UnixMilli())
fmt.Println("微秒", now.UnixMicro())
fmt.Println("纳秒", now.UnixNano())

输出

1
2
3
4
5
2023-04-13 13:10:17.8577739 +0800 CST m=+0.004403301
秒 1681362617
豪秒 1681362617857
微秒 1681362617857773
纳秒 1681362617857773900

time.Now 返回的结构是 time.Time

1
2
3
4
5
type Time struct {
wall uint64
ext int64
loc *Location
}

按go的约定,这个结构里的数据都是私有变量,对于我们使用来说没有价值。

2. 日期时间格式化

特别注意:go的格式化字符串不是常见的 yy-MM-dd HH:mm:ss,而是2006-01-02 15:04:05 Go的成立日期。

1
2
fmt.Println(now.Format("2006-01-02 15:04:05"))
fmt.Println(now.Format("06-1-2 3:4:5"))

输出

1
2
2023-04-13 14:21:21
23-4-13 2:21:21

格式化字符说明:

字符 说明
1 月份
01 月份,保证两位数字,1月会输出01
2 日期
02 日期,保证两位数字,2日会输出02
3 小时,12小时制
03 小时,保证两位数字,3时会输出03
15 小时,24小时制,保证两位数字,3时会输出03
4 分钟
04 分钟,保证两位数字,4分会输出04
5
05 秒,保证两位数字,5秒会输出05
06 年,输出最后两位
2006 年,输出4位
.000 毫秒

可以快速记忆: 1月2日3时4分5秒6年

3. 字符串日期时间转time

通过time.Parse来把字符串转为 Time 时间对象

1
2
3
4
5
6
t, err := time.Parse("2006-01-02 15:04:05", "2023-04-14 07:03:04")
if err == nil {
fmt.Print(t.Year())
} else {
fmt.Print(err)
}

输出: 2023

如果出错了,会在返回的err 里有说明。比如:

1
2
3
4
5
6
t, err := time.Parse("2006-01-02 15:04:05", "04-14 07:03:04")
if err == nil {
fmt.Print(t.Year())
} else {
fmt.Print(err)
}

就会输出

1
parsing time "04-14 07:03:04" as "2006-01-02 15:04:05": cannot parse "04-14 07:03:04" as "2006"

4. 获取年/月/周/日/时/分/秒

1
2
3
4
5
6
7
8
9
10
11
12
13
t, err := time.Parse("2006-01-02 15:04:05", "04-14 07:03:04")

fmt.Println("年", t.Year())
fmt.Println("月", t.Month())
fmt.Println("月", t.Month() == 4)
fmt.Println("日", t.Day())
fmt.Println("时", t.Hour())
fmt.Println("分", t.Minute())
fmt.Println("秒", t.Second())
fmt.Println("星期几", t.Weekday())
year, week := t.ISOWeek()
fmt.Println("某年第几周", year, week)
fmt.Println("当年第几天", t.YearDay())

输出

1
2
3
4
5
6
7
8
9
10
年 2023
月 April
月 true
日 14
时 7
分 3
秒 4
星期几 Friday
某年第几周 2023 15
当年第几天 104
文章目录
  1. 1. 1. 获取当前时间
  2. 2. 2. 日期时间格式化
  3. 3. 3. 字符串日期时间转time
  4. 4. 4. 获取年/月/周/日/时/分/秒