时间类型Time
时间类型在实际开发中使用频率很高,Go中使用time包下的Time结构体,时间类型默认显示为UTC,经常需要把时间转换为字符串。
案例:
package main
import (
"fmt"
"time"
)
func main() {
var t1 time.Time
fmt.Println(t1) // 0001-01-01 00:00:00 +0000 UTC
t2 := time.Now()
fmt.Println(t2) // 2022-12-12 21:25:26.7342993 +0800 CST m=+0.001027901
// 根据时间戳创建时间,
t3 := time.Unix(0, t2.UnixNano())
fmt.Println(t2.String()) // 2022-12-12 21:27:26.2361754 +0800 CST m=+0.002799501
fmt.Println(t3) // 2022-12-12 21:27:26.2361754 +0800 CST
t4 := time.Date(2022, 12, 12, 13, 14, 15, 0, time.Local)
fmt.Println(t4) // 2022-12-12 21:27:26.2361754 +0800 CST m=+0.002799501
t5 := time.Now()
fmt.Println(t5.Year()) // 年
fmt.Println(int(t5.Month())) // 月
fmt.Println(t5.Day()) // 日
fmt.Println(t5.Date()) // 三个参数: 年,月,日
fmt.Println(t5.Hour()) // 时
fmt.Println(t5.Minute()) // 分
fmt.Println(t5.Second()) // 秒
fmt.Println(t5.Clock()) // 三个参数: 时,分,秒
fmt.Println(t5.Nanosecond()) // 纳秒 390972000
fmt.Println(t5.Unix()) // 秒差 1670851989
fmt.Println(t5.UnixNano()) // 纳秒差 1670851989390972000
// 时间和string相互转换
t6 := time.Now()
s6 := t6.Format("2006/01/02 03:04:05 006")
fmt.Println(s6)
f6 := t6.Format("2006-01-02 15:04:05")
fmt.Println(f6)
// string类型转换为Time
s7 := "2022/12/12 09:35:37 022"
t7, _ := time.Parse("2006/01/02 03:04:05 006", s7)
fmt.Println(t7)
f7 := "2022-12-12 21:38:20"
t8, _ := time.Parse("2006-01-02 15:04:05", f7)
fmt.Println(t8)
}
常用的数学函数
案例:
package main
import (
"fmt"
"math"
"math/rand"
"time"
)
func main() {
// 数学函数
var a, b float64 = 12.3, 9.6
fmt.Println("向下取整:", math.Floor(a)) // 12
fmt.Println("向上取整:", math.Ceil(b)) // 10
// 绝对值
fmt.Println("绝对值:", math.Abs(-11)) // 11
num, decimal := math.Modf(a)
fmt.Println("整数位和小数位:", num, decimal) //12 0.3000
fmt.Println("返回最大值:", math.Max(a, b))
fmt.Println("返回最小值:", math.Min(a, b))
fmt.Println("x的y次方:", math.Pow(2, 3)) //8
fmt.Println("四舍五入:", math.Round(a)) //12
fmt.Println("四舍五入:", math.Round(b)) // 10
// 随机数
// 设置随机数的种子,不设置随机数结果每次运行都相同
rand.Seed(time.Now().UnixNano())
fmt.Println("产生小于10的随机数:", rand.Int63n(10))
fmt.Println("产生小于10的随机数:", rand.Int63n(10))
}