go标准库三 | 青训营笔记

132 阅读6分钟

这是我参与「第五届青训营」伴学笔记创作活动的第10天。

time

  • time包提供测量和显示时间的功能

基本使用

    now := time.Now() //获取当前时间 2023-01-26 22:26:28.7819735 +0800 CST m=+0.003571701
    year := now.Year()
    month := now.Month()
    day := now.Day()
    hour := now.Hour()
    minute := now.Minute()
    second := now.Second()
    fmt.Printf("%d-%02d-%02d %02d:%02d:%02d\n", year, month, day, hour, minute, second)
    //2023-01-26 22:28:3
    fmt.Printf("%T,%T,%T,%T,%T,%T,%T\n", now, year, month, day, hour, minute, second)
    //time.Time,int,time.Month,int,int,int,int
}
    

时间戳

  • 时间戳是自1970年1月1日(08:00:00GMT)至当前时间的总毫秒数。
  • 用途:cookies有效期、接口加密等
  • 获取时间戳:
    now := time.Now()
    now.Unix()
    //纳秒时间戳
    now := time.Now()
    now.UnixNano()
    //将时间戳转化为普通的时间格式
    timestamp := time.Now().Unix()
    timeObj := time.Unix(timestamp,0)

操作时间

Add

package main

import (
    "fmt"
    "time"
)

func add(h, m, s, mls, msc, ns time.Duration) {
    now := time.Now()
    fmt.Println(now.Add(time.Hour*h + time.Minute*m + time.Second*s + time.Millisecond*mls + time.Microsecond*msc + time.Nanosecond*ns))
}

func main() {
    test4(3, 4, 5, 6, 7, 8)
}
  • 不能增加年月日,只能增加以下内容
const (
    Nanosecond  Duration = 1
    Microsecond          = 1000 * Nanosecond
    Millisecond          = 1000 * Microsecond
    Second               = 1000 * Millisecond
    Minute               = 60 * Second
    Hour                 = 60 * Minute
)

Sub

func sub() {
    now := time.Now()
    targetTime := now.Add(time.Hour)
    // 目标时间与此时相比相差1h0m0s
    fmt.Println(targetTime.Sub(now))
}

其他

func (t Time) Equal(u Time) bool //判断两个时间是否相同
func (t Time) Before(u Time) bool //如果t代表的时间点在u之前,返回真,否则返回假
func (t Time) After(u Time) bool //如果t代表的时间点在u之后,返回真,否则返回假

定时器

  • 使用time.Tick(时间间隔)来设置定时器,定时器本质上是一个通道
    ticker := time.Tick(time.Second)
    for i := range ticker {
        fmt.Println(i)
    }

时间格式化

  • 使用Format进行格式化。需要注意的是go语言中格式化时间模板是go的诞生时间:2006年1月2日15时04分
    now := time.Now()
    // 格式化的模板为Go的出生时间2006年1月2号15点04分 Mon Jan
    // 24小时制
    fmt.Println(now.Format("2006-01-02 15:04:05.000 Mon Jan"))
    // 12小时制 如果想格式化为12小时的方式,需要指定PM
    fmt.Println(now.Format("2006-01-02 03:04:05.000 PM Mon Jan"))
    fmt.Println(now.Format("2006/01/02 15:04"))
    fmt.Println(now.Format("15:04 2006/01/02"))
    fmt.Println(now.Format("2006/01/02"))

解析字符串格式的时间

    now := time.Now()
    fmt.Println(now)
    // 加载时区
    loc, err := time.LoadLocation("Asia/Shanghai")
    if err != nil {
        fmt.Println(err)
        return
    }
    // 按照指定时区和指定格式解析字符串时间
    timeObj, err := time.ParseInLocation("2006/01/02 15:04:05", "2023/01/28 22:15:20", loc)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(timeObj)

sort

  • sort包提供了排序切片和用户自定义数据集以及相关功能的函数。
  • sort包主要针对[]int[]float64[]string、以及其他自定义切片的排序。已经内置了对这三类切片的排序方式。

接口

type Interface interface {
    Len() int           // Len方法返回集合中的元素个数
    Less(i, j int) bool // i>j,该方法返回索引i的元素是否比索引j的元素小、
    Swap(i, j int)      // 交换i, j的值
}

函数

func Ints(a []int)
func IntsAreSorted(a []int) bool
func SearchInts(a []int, x int) int
func Float64s(a []float64)
func Float64sAreSorted(a []float64) bool
func SearchFloat64s(a []float64, x float64) int
func SearchFloat64s(a []flaot64, x float64) bool
func Strings(a []string)
func StringsAreSorted(a []string) bool
func SearchStrings(a []string, x string) int
func Sort(data Interface)
func Stable(data Interface)
func Reverse(data Interface) Interface
func ISSorted(data Interface) bool
func Search(n int, f func(int) bool) int

通过实现接口来调用函数

package main

import (
    "fmt"
    "sort"
)

type NewInts []uint

func (n NewInts) Len() int {
    return len(n)
}

func (n NewInts) Less(i, j int) bool {
    fmt.Println(i, j, n[i] < n[j], n)
    return n[i] < n[j]
}

func (n NewInts) Swap(i, j int) {
    n[i], n[j] = n[j], n[i]
}

func main() {
    n := []uint{1,3,2}
    sort.Sort(NewInts(n))
    fmt.Println(n)
}

math

  • math包包含一些常量和一些数学计算函数

常量

 fmt.Printf("float64的最大值是:%.f\n", math.MaxFloat64)
 fmt.Printf("float64的最小值是:%.f\n", math.SmallestNonzeroFloat64)
 fmt.Printf("float32的最大值是:%.f\n", math.MaxFloat32)
 fmt.Printf("float32的最小值是:%.f\n", math.SmallestNonzeroFloat32)
 fmt.Printf("Int8的最大值是:%d\n", math.MaxInt8)
 fmt.Printf("Int8的最小值是:%d\n", math.MinInt8)
 fmt.Printf("Uint8的最大值是:%d\n", math.MaxUint8)
 fmt.Printf("Int16的最大值是:%d\n", math.MaxInt16)
 fmt.Printf("Int16的最小值是:%d\n", math.MinInt16)
 fmt.Printf("Uint16的最大值是:%d\n", math.MaxUint16)
 fmt.Printf("Int32的最大值是:%d\n", math.MaxInt32)
 fmt.Printf("Int32的最小值是:%d\n", math.MinInt32)
 fmt.Printf("Uint32的最大值是:%d\n", math.MaxUint32)
 fmt.Printf("Int64的最大值是:%d\n", math.MaxInt64)
 fmt.Printf("Int64的最小值是:%d\n", math.MinInt64)
 fmt.Printf("圆周率默认为:%.200f\n", math.Pi)
 
 //运行结果
float64的最大值是:179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368
float64的最小值是:0
float32的最大值是:340282346638528859811704183484516925440
float32的最小值是:0
Int8的最大值是:127
Int8的最小值是:-128
Uint8的最大值是:255
Int16的最大值是:32767
Int16的最小值是:-32768
Uint16的最大值是:65535
Int32的最大值是:2147483647
Int32的最小值是:-2147483648
Uint32的最大值是:4294967295
Int64的最大值是:9223372036854775807
Int64的最小值是:-9223372036854775808
圆周率默认为:3.14159265358979311599796346854418516159057617187500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

常用函数

package main

import (
	"fmt"
	"math"
)

func main() {
	/*
		取绝对值,函数签名如下:
		func Abs(x float64) float64
	*/
	fmt.Printf("[-3.14]的绝对值为:[%.2f]\n", math.Abs(-3.14))

	/*
		取xy次方,函数签名如下:
		func Pow(x, y float64) float64
	*/
	fmt.Printf("[2]的16次方为:[%.f]\n", math.Pow(2, 16))

	/*
		取余数,函数签名如下:
		func Pow10(n int) float64
	*/
	fmt.Printf("10的[3]次方为:[%.f]\n", math.Pow10(3))

	/*
		取x的开平方,函数签名如下:
		func Sqrt(x float64) float64
	*/
	fmt.Printf("[64]的开平方为:[%.f]\n", math.Sqrt(64))

	/*
		取x的开立方,函数签名如下:
		func Cbrt(x float64) float64
	*/
	fmt.Printf("[27]的开立方为:[%.f]\n", math.Cbrt(27))

	/*
		向上取整,函数签名如下:
		func Ceil(x float64) float64
	*/
	fmt.Printf("[3.14]向上取整为:[%.f]\n", math.Ceil(3.14))

	/*
		向下取整,函数签名如下:
		func Floor(x float64) float64
	*/
	fmt.Printf("[8.75]向下取整为:[%.f]\n", math.Floor(8.75))

	/*
		取余数,函数签名如下:
		func Floor(x float64) float64
	*/
	fmt.Printf("[10/3]的余数为:[%.f]\n", math.Mod(10, 3))

	/*
		分别取整数和小数部分,函数签名如下:
		func Modf(f float64) (int float64, frac float64)
	*/
	Integer, Decimal := math.Modf(3.14159265358979)
	fmt.Printf("[3.14159265358979]的整数部分为:[%.f],小数部分为:[%.14f]\n", Integer, Decimal)
}