time库
目录
time模块
打印当前时间戳
fmt.Println(time.Now().Unix())# 1606879472
str格式化时间
time.Now() 是要格式化的时间
fmt.Println(time.Now().Format("2006-01-02 15:04:05")) # 这是个奇葩,必须是这个时间点, 据说是go诞生之日, 记忆方法:6-1-2-3-4-5
# 2020-12-02 11:25:12
时间戳转str格式化时间
str_time := time.Unix(1606879911, 0).Format("2006-01-02 15:04:05")
fmt.Println(str_time)
# 2020-12-02 11:31:51
str格式化时间转时间戳
the_time := time.Date(2020, 12, 1, 1, 00, 0, 0,time.Local)
unix_time := the_time.Unix()
fmt.Println(unix_time)# 1606755600
time.Parse格式化时间转时间戳 (UTC时区)
the_time, err := time.Parse("2006-01-02 15:04:05", "2020-12-01 09:04:41")
if err == nil {
unix_time := the_time.Unix()
fmt.Println(unix_time)
}
# 1606813481
time.ParseInLocation自定义时间转换
time.ParseInLocation无市区问题
time.Parse有时区问题
func main() {
the_time, err := time.ParseInLocation("20060102-15:04:05", "20221117-14:00:00", time.Local)
if err != nil {
fmt.Println("err")
}
fmt.Println(the_time) // fmt.Println(the_time)
fmt.Println(the_time.Unix()) //1668664800
}
time.ParseInLocation字符串时间转时间戳(本地时区)
the_time, err := time.ParseInLocation("2006-01-02 15:04:05", "2023-01-01 00:00:00", time.Local)
if err != nil {
fmt.Println("时间错误")
return
}
fmt.Println(the_time.Unix()) //1672502400
time.Parse和time.Format的区别
在windows下,time.Parse()的时区和time.Format()的时区是一致的。但是在linux环境下,time.Parse()的默认时区是UTC(与我们使用的标准时间CST相差8个小时),time.Format()的时区默认是本地,两者如果不处理好就会导致错误。具体可以做如下一个操作,找一台linux主机,将其/etc/localtime由Shanghai更换为UTC,然后分别执行如下代码,看下输出的区别:
func main() {
t, err := time.Parse("2006-01-02 15:04:05", "2017-12-03 22:01:02")
localTime, err := time.ParseInLocation("2006-01-02 15:04:05", "2017-12-03 22:01:02", time.Local)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(t)
fmt.Println(time.Now())
fmt.Println(time.Now().Sub(t).Seconds())
fmt.Println(localTime)
}
分别使用time.Parse和time.ParseInLocation分别算下两个时间之间的差值,看下哪一个求出的值是正确的?
ParseTime万能格式--字符串时间转时间戳(本地时区)
func demo() {
str1 := "2022-1-1" //1.yyyy-m-d
str2 := "2022-01-01" //2.yyyy-mm-dd
str3 := "2022/01/01" //3:yyyy/mm/dd
str4 := "2022/1/1" //4:yyyy/m/d
str5 := "2022-1-1 00-00-00" //5:yyyy-mm-dd hh-mm-ss
str6 := "2022-1-1 00:00:00" //6:yyyy-mm-dd hh:mm:ss
str7 := "2022-1-1 00/00/00" //7:yyyy-mm-dd hh/mm/ss
str8 := "2022/1/1 00-00-00" //8:yyyy/mm/dd hh-mm-ss
str9 := "2022/1/1 00:00:00" //9:yyyy/mm/dd hh:mm:ss
str10 := "2022/1/1 00/00/00" //10:yyyy/mm/dd hh/mm/ss
fmt.Println(ParseTime(str10))
}
func ParseTime(strTime string) (int64, error) {
strTime = strings.TrimSpace(strTime)
s := strings.Split(strTime, " ")
layout := "2006-1-2 15-04-05" //默认格式
switch len(s) {
case 1: //年月日
if strings.Contains(strTime, "-") {
layout = "2006-1-2" //1,2:yyy-m-d,yyy-mm-dd
} else {
layout = "2006/1/2" //3,4:yyyy/mm/dd,yyyy/m/d
}
case 2: //年月日时分秒
if strings.Contains(s[0], "-") {
if strings.Contains(s[1], "-") {
layout = "2006-1-2 15-04-05" //5:yyyy-mm-dd hh-mm-ss
} else {
if strings.Contains(s[1], ":") {
layout = "2006-1-2 15:04:05" //6:yyyy-mm-dd hh:mm:ss
} else {
layout = "2006-1-2 15/04/05" //7:yyyy-mm-dd hh/mm/ss
}
}
} else {
if strings.Contains(s[1], "-") {
layout = "2006/1/2 15-04-05" //8:yyyy/mm/dd hh-mm-ss
} else {
if strings.Contains(s[1], ":") {
layout = "2006/1/2 15:04:05" //9:yyyy/mm/dd hh:mm:ss
} else {
layout = "2006/1/2 15/04/05" //10:yyyy/mm/dd hh/mm/ss
}
}
}
}
shipTsInt, err := time.ParseInLocation(layout, strTime, time.Local)
if err != nil {
fmt.Println("err:", err)
return 0, err
}
return shipTsInt.Unix(), nil
}
Format
now := time.Now()
fmt.Println(now) //2021-07-13 11:26:39.500074 +0800 CST m=+0.002081543
edidate := now.Format("20060102150405")
fmt.Println(edidate) // 20210713112639
int型时间数字处理
timestamp := int64(1640534400)
now := time.Unix(timestamp, 0).Format("2006-01")
pg时间格式timestamp读取到结构体
import "time"
sqlstr := `
select
coalesce(id,0) as id,
coalesce(code,'') as code,
coalesce(name,'') as name,
coalesce(company,'') as company,
coalesce(updated_at,'1970-01-01'::timestamp) as updated_at
from bike_brand
where 1=1
`
sqlstr += qstr
err := o.DbRo.QueryRow(sqlstr).Scan(&r.Id, &r.Code, &r.Name, &r.Company, &r.UpdatedAt)
type Info struct {
Id int `json:"id"`
Code string `json:"code"`
Name string `json:"name"`
Company string `json:"company"`
UpdatedAt time.Time `json:"updated_at"`
}
迭代日期
package main
import (
"fmt"
"time"
)
func main() {
start := "2023-10-10"
end := "2023-10-12"
// 解析开始和结束日期
startDate, _ := time.Parse("2006-01-02", start)
endDate, _ := time.Parse("2006-01-02", end)
slices := generateSlices(startDate, endDate)
fmt.Println(slices) //[[2023-10-10 00:00:00 2023-10-10 23:59:59] [2023-10-11 00:00:00 2023-10-11 23:59:59] [2023-10-12 00:00:00 2023-10-12 23:59:59]]
}
func generateSlices(startDate, endDate time.Time) [][]string {
var slices [][]string
// 迭代日期并生成切片
currentDate := startDate
for !currentDate.After(endDate) {
nextDate := currentDate.AddDate(0, 0, 1)
slice := []string{currentDate.Format("2006-01-02 15:04:05"), nextDate.Add(-time.Second).Format("2006-01-02 15:04:05")}
slices = append(slices, slice)
currentDate = nextDate
}
return slices
}
示例
最后再给出一个输出当前时间年、月、日、时等不同信息的示例代码,如下:
package main
import(
"fmt"
"time"
)
func main(){
t := time.Now()
y,m,d := t.Date()
today := time.Now().Format("2006-01-02")
datetime := time.Now().Format("2006-01-02 15:04:05")//后面的参数是固定的 否则将无法正常输出
fmt.Println("time is : ",t )
fmt.Println("y m d is : ",y,m,d )
fmt.Println("now is :",today)
fmt.Println("now is :",datetime)
}
2020-12-02 11:42:48.606258 +0800 CST m=+0.000126668
2020 December 2
2020-12-02
2020-12-02 11:42:48
时间分布算法
func getDates(startTime, endTime int64, number int) []string {
//取时间范围的点,首位一个点,中间点平均分布
// 计算时间差,单位是秒
timeDiff := endTime - startTime
// 如果时间差小于等于6天,则返回全部时间范围内的点
if timeDiff <= (int64(number)-1)*86400 {
dates := make([]string, 0, timeDiff/86400+1)
for t := startTime; t <= endTime; t += 86400 {
dates = append(dates, time.Unix(t, 0).Format("2006-01-02"))
}
return dates
}
// 生成number个点的时间戳
timestamps := make([]int64, number)
timestamps[0] = startTime
timestamps[number-1] = endTime
step := (timeDiff / 86400) / (int64(number) - 1)
for i := number - 2; i > 0; i-- {
timestamps[i] = endTime - (step*86400)*int64(number-1-i)
}
// 转换为日期字符串
dates := make([]string, number)
for i, t := range timestamps {
dates[i] = time.Unix(t, 0).Format("2006-01-02")
}
return dates
}
func main() {
a := getDates(1714492800, 1716134400, 7)
fmt.Println(a)
}
时间运算
now := time.Now()
time1 := now.AddDate(0, 0, -1).Format("2006-01-02")
fmt.Println(time1)
time2 := now.Add(-1 * 24 * time.Hour)
fmt.Println(time2)
选择了IT,必定终身学习