go日期时间函数+常用内建函数+错误处理

// 时间日期函数包
import "time" 

// 1. 当前时间 time.Now()-->time.Time类型 

// 2. now:=time.Now()  now.Year() now.Month() ->May int(now.Month)->5

// 格式化日期时间

// 方式1   Sprintf("%d")配合 now.Year() 返回格式化字符串

// 方式2   now.Format("2006 01 02 15:04:05")  只取年now.Format("2006")  这个设计太有意思了

// time.Unix 时间戳  UnixNano 纳秒时间戳


func T1() {
        // 指定数据创建一个time.Date 注意参数 月份time.October 时间精确到毫秒 时区必须有 UTC/Local
        birthday := time.Date(1992, time.June , 1, 12, 20, 58,666, time.Local)
    
    // type is time.Time,value is 1992-06-01 12:20:58.000000666 +0800 CST
        fmt.Printf("type is %T,value is %v \n", birthday, birthday)
    
        // 日期格式化 Sprintf
        strbirthday := fmt.Sprintf("%d年%d月%d日", birthday.Year(), birthday.Month(),      birthday.Day())
        // type is string,value is 1992年6月1日
        fmt.Printf("type is %T,value is %v \n", strbirthday, strbirthday)
        
    // 日期格式化 Format
        str := birthday.Format("2006/01/02 15:04:05")
    
        // type is string,value is 1992/06/01 12:20:58
        fmt.Printf("type is %T,value is %v \n", str, str)
}

内建函数

  1. len(seq) 返回序列的长度 string array slice map chan
  2. new(type) 用于分配内存,主要用于分配值类型 --> 返回的是指针
  3. make() 用于分配内存,主要用来分配引用类型
  4. panic() 抛出错误
  5. recover() 捕获错误

错误处理

默认情况下,当发生错误(panic)后,程序就会退出(崩溃)

希望可以捕获错误,进行处理,保证程序可以继续执行,需要一个处理错误的机制

golang错误处理机制

panic +defer + recover

程序抛出panic异常,defer中通过recover捕获这个异常,然后进行处理

 defer func () { // defer + 匿名函数 + revocer
                        err := recover() //内置函数 可以捕获到异常
                        if err != nil {
                                fmt.Println(err) // 打印错误
                                // dosomething 
                        }       
                }()

自定义错误

  • errors.New("错误说明") 返回一个error类型 表示一个错误

  • panic()可以接受interface{}类型的值作为参数,可以接受error类型的变量,输出错误信息,并退出程序