Golang 时间常用取昨天日期的字符串(比如今天 2019-12-27 14:48) 结果为(2019-12-26)

4,221 阅读1分钟

取昨天的日( 不包含 时分秒)

时间常用取昨天日期的字符串(比如今天 2019-12-27 14:48) 结果为(2019-12-26)

go测试代码

package main

import (
    "fmt"
    "time"
)

func main() {
	t := time.Now()
	newTime := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
	ld1Time := newTime.AddDate(0, 0, -1)


	logDay := ld1Time.Format("20060102")
	fmt.Println(newTime)

	fmt.Println(ld1Time)
	fmt.Println(logDay)

}


获取当前时间和日期

t := time.Now()

构造 当天零点时间

`` newTime := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())

### 减一天
ld1Time := newTime.AddDate(0, 0, -1)
#### 格式化day 字符串。
fmt.Println(logDay)

输出结果

2019-12-27 00:00:00 +0800 CST
2019-12-26 00:00:00 +0800 CST
20191226

总结反思:

20191226 就是我们要的结果,那么如果我们想要2019-12-26 该怎么办呢? 你想想吧。

最好自己动脑思考才能提升, 小提升:: 可以

	logDay := ld1Time.Format("2006-01-02")