package main
import (  "fmt"  "time")
func main() {  // 日期和时间相关函数和方法的使用
  // 1.获取当前时间  now := time.Now()  // now = 2022-10-16 12:33:25.9941447 +0800 CST m=+0.002308001, type = time.Time  fmt.Printf("now = %v, type = %T", now, now)
  // 去除now中的年 月 日 时分秒  fmt.Printf("年 = %v\n", now.Year())  fmt.Printf("月 = %v\n", now.Month())  fmt.Printf("月 = %v\n", int(now.Month()))  fmt.Printf("日 = %v\n", now.Day())  fmt.Printf("时 = %v\n", now.Hour())  fmt.Printf("分 = %v\n", now.Minute())  fmt.Printf("秒 = %v\n", now.Second())
  // 格式化时间  fmt.Printf("当前年月日 %d-%d-%d %d:%d:%d \n", now.Year(),    now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second())  // 把字符串给一个变量  dataStr := fmt.Sprintf("当前年月日 %d-%d-%d %d:%d:%d \n", now.Year(),    now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second())
  fmt.Printf("dataStr = %v", dataStr)
  // 格式化第二种写法  // 2006/01/02 15:04:05 这个字符串是固定的,必须这样写  // 数字不能乱改,间隔可以改  // 可按需求组合  fmt.Printf(now.Format("2006/01/02 15:04:05"))  // 2022/10/16 14:38:34  fmt.Println()  fmt.Printf(now.Format("2006-01-02"))  // 2022-10-16  fmt.Println()  fmt.Printf(now.Format("15:04:06"))  // 14:38:22  fmt.Println()
  // 只取月份  fmt.Printf(now.Format("01"))  fmt.Println()  // 只取年  fmt.Printf(now.Format("2006"))  fmt.Println()
  // 时间的常量应用
  // // 结合Sleep使用  // // 每个一秒打印一个数字,打印到100就退出  // i := 0  // for {  //   i++  //   fmt.Println("i = ", i)  //   //休眠  //   time.Sleep(time.Second)  //   if 1 == 100 {  //     break  //   }  // }
  // 每隔0.1秒打印一个数字,到100时退出  i := 0  for {    i++    fmt.Println("new i = ", i)    // 0.1秒 =  Millisecond * 100    time.Sleep(time.Millisecond * 100)    if i == 100 {      break    }  }
  // Unix 和 UnixNano
  fmt.Printf("Unix 时间戳:=%v , UnixNano时间戳= %v\n", now.Unix(), now.UnixNano())  // Unix 时间戳:=1665904263 , UnixNano时间戳= 1665904263830448500  }
评论