go语言中日期字符串与时间戳互转
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| package main
import ( "fmt" "time" )
func main() { now := time.Now() fmt.Println("当前时间:", now)
h, _ := time.ParseDuration("2h") nowAfter2Hour := now.Add(h) fmt.Println("两小时之后的时间:", nowAfter2Hour)
negativeH, _ := time.ParseDuration("-2h") nowBefore2Hour := now.Add(negativeH) fmt.Println("两小时之前的时间:", nowBefore2Hour)
datetime1 := "2018-10-22 11:17:20" datetime2 := "2018-10-23 11:17:20"
timeLayout := "2006-01-02 15:04:05"
tmp1, _ := time.Parse(timeLayout, datetime1) tmp2, _ := time.Parse(timeLayout, datetime2) timestamp1 := tmp1.Unix() timestamp2 := tmp2.Unix()
subtime := (timestamp2 - timestamp1) / 3600 / 24
fmt.Println("时间差天数:", subtime)
ProfitAmount := (0.02 * 12 / 365) * 10000 * (float64(subtime)) fmt.Println("利润", ProfitAmount) datetime1 = time.Unix(timestamp1, 0).Format(timeLayout) datetime2 = time.Unix(timestamp2, 0).Format(timeLayout) datetime3 := time.Unix(subtime, 0).Format(timeLayout) fmt.Println(datetime3)
datetime3day := time.Unix(subtime, 0).Day() fmt.Println(datetime3day)
m, _ := time.ParseDuration("10m") nowAfter10Minute := now.Add(m) fmt.Println("十分钟之后的时间:", nowAfter10Minute)
negativeM, _ := time.ParseDuration("-10m") nowBefore10Minute := now.Add(negativeM) fmt.Println("十分钟之前的时间:", nowBefore10Minute)
s, _ := time.ParseDuration("30s") nowAfter30Second := now.Add(s) fmt.Println("30s之后的时间:", nowAfter30Second)
negativeS, _ := time.ParseDuration("-30s") nowBefore30Second := now.Add(negativeS) fmt.Println("30s之前的时间:", nowBefore30Second)
fmt.Println("1年2个月3天之后的时间:", now.AddDate(1, 2, 3))
fmt.Println("2年3个月4天之前的时间:", now.AddDate(-2, -3, -4))
}
|
Go语言时间处理
格式化时间
1 2
| fmt.Println(time.Now().Format("2006-01-02 15:04:05"))
|
时间戳转换为格式化字符串
1 2 3
| str_time := time.Unix(1389058332, 0).Format("2006-01-02 15:04:05") fmt.Println(str_time)
|
格式化字符串转时间
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| the_time := time.Date(2014, 1, 7, 5, 50, 4, 0, time.Local) unix_time := the_time.Unix() fmt.Println(unix_time)
=====================
the_time, err := time.Parse("2006-01-02 15:04:05", "2014-01-08 09:04:41") if err == nil { unix_time := the_time.Unix() fmt.Println(unix_time) }
|