时间格式在程序、数据库、日志信息中扮演着非常重要的角色,选择合适的格式能为我们的工作带来编辑。在Go语言中可以使用time包实现我们基础的需求。

导入包

import (
   "time"
   "fmt"
)

时间输出以及格式化

package main

import (
   "time"
   "fmt"
)

//时间函数以及时间格式化

func  main(){
   now  := time.Now()
   //Year = now.Year()
   //Mouth  = now.Month()
   //Day  =  now.Day()
   //时间格式化输出 Printf输出
   fmt.Printf("当前时间为: %d-%d-%d %d:%d:%dn",now.Year(),now.Month(),now.Day(),now.Hour(),now.Minute(),now.Second())
//fmt.Sprintf 格式化输出
  dateString := fmt.Sprintf("当前时间为: %d-%d-%d %d:%d:%dn",now.Year(),now.Month(),now.Day(),now.Hour(),now.Minute(),now.Second())
   fmt.Println(dateString)
 //now.Format 方法格式化
  fmt.Println(now.Format("2006-01-02 15:04:05"))
  fmt.Println(now.Format("2006/01/02 15:04:05"))
  fmt.Println(now.Format("2006/01/02"))//年月日
  fmt.Println(now.Format("15:04:05"))//时分秒


   }

输出结果

image.png


注意事项:用now.Format()方式 其字符串的格式是特定的"2006-01-02 15:04:05",我们在使用的时候可以根据需求对其更改,例如只显示年月日,以及时间的间隔符号等。