Golang 日期处理丶函数执行耗时丶内置函数

一.日期处理

 1 func testDate() {
 2     // 获取当前时间
 3     now := time.Now()
 4     fmt.Printf("当前时间:%v , 时间的类型:%T \n", now, now)
 5     fmt.Printf("当前时间的年=%v月=%v日=%v时=%v分=%v秒=%v \n", now.Year(), int(now.Month()), now.Day(), now.Hour(), now.Minute(), now.Second())
 6     // 格式化输出时间
 7     datestr := fmt.Sprintf("当前时间的%v-%02d-%v %v:%v:%v", now.Year(), int(now.Month()), now.Day(), now.Hour(), now.Minute(), now.Second())
 8     fmt.Println("格式化输出时间:", datestr)
 9     // 第二种格式化输出时间: 固定格式  2006-01-02 15:04:05
10     fmt.Println("第二种格式化输出时间", now.Format("2006/1/02 15:04:05"))
11     fmt.Println("第二种格式化输出时间", now.Format("15:04:05"))
12     // 时间单位长量:“ns”,“us”(或“µs”),“ms”,“s”,“m”,“h”
13     fmt.Printf("时:%v, 分:%v, 秒:%v, 毫秒: %v, 微秒:%v, 纳秒:%v \n", time.Hour, time.Minute, time.Second, time.Microsecond, time.Microsecond, time.Nanosecond)
14     // 常用作用:在程序中获得100毫秒
15     fmt.Printf("100毫秒=%v\n", 100*time.Millisecond)
16     // 休眠 Sleep
17     for i := 0; i < 5; i++ {
18         time.Sleep(100 * time.Millisecond)
19         fmt.Println("休眠一百毫秒后输出:", i)
20     }
21     // unix时间戳1970-1-1到现在的秒数
22     fmt.Println("unix时间戳:", now.Unix())
23     // unixnano时间戳1970-1-1到现在的纳秒数
24     fmt.Println("unixnano时间戳:", now.UnixNano())
25 
26     // 该函数可以解析持续时间字符串。持续时间字符串是带符号的十进制数字序列,带有可选的分数和单位后缀,例如“100ms”,“2.3h”或“4h35m”
27     comp, _ := time.ParseDuration("5h30m40s")
28     fmt.Printf("Time ParseDuration Type:%T , Value:%v \n", comp, comp)
29     // 日期加减: time.Duration
30     later := now.Add(comp)
31     fmt.Println("日期加5h30m40s=", later)
32     duration := later.Sub(now)
33     fmt.Printf("相差%.2f小时.....原值:%v \n", duration.Hours(), duration)
34 
35     // 字符串转日期
36     t1, _ := time.Parse("2023-08-24 14:30:22", "2006-01-02 15:04:05")
37     fmt.Printf("字符串转日期:%v , 时间的类型:%T \n", t1, t1)
38 }

二.函数执行耗时

1 // 统计函数执行耗时
2 func testTimeExercise(afunc func()) int64 {
3     start := time.Now().UnixNano()
4     afunc()
5     // time.Sleep(2 * time.Second)
6     end := time.Now().UnixNano()
7 
8     return ((end - start) / 1e6) // 纳秒转微秒
9 }

三.内置函数

1 // 内置函数
2 func testBuiltin() {
3     // len() 返回字符串,数组的长度,比如:string  array  slice   map   channel
4     fmt.Println("得到字符串的长度(一个中文utf8编码占3个字节):", len("hello 中国!"))
5     // new() 用来分配内存,主要用来分配值类型,比如:int  float32  struct...返回的是指针
6     var pt1 *int = new(int)
7     fmt.Printf("类型:%T , 地址:%v , 值:%v , 指向的值:%v , 指向值的地址:%v \n", pt1, &pt1, pt1, *pt1, &(*pt1))
8     // make()  用来分配内存,主要用来分配引用类型,比如:channel  map  slice
9 }

 

posted @ 2023-09-11 10:50  看一百次夜空里的深蓝  阅读(85)  评论(0编辑  收藏  举报