Golang 获取时间格式化

package main

import (
	"fmt"
	"time"
)

func main(){
	now := time.Now()
	fmt.Printf("%T %v",now,now)
	fmt.Println()
	fmt.Printf("年:%v 、",now.Year())
	fmt.Printf("月:%v 、",int(now.Month()))
	fmt.Printf("月:%v 、",now.Month())
	fmt.Printf("日:%v 、",now.Day())
	fmt.Printf("时:%v 、",now.Hour())
	fmt.Printf("分:%v 、",now.Minute())
	fmt.Printf("秒:%v ",now.Second())

	fmt.Println()
	//方式一:格式化时间
	dateStr := fmt.Sprintf("%d-%d-%d %d:%d:%d",now.Year(),int(now.Month()),
							now.Day(),now.Hour(),now.Minute(),now.Second())

	//2020-3-18 19:25:7
	fmt.Printf("%s",dateStr)
	fmt.Println()
	dateStr1 := fmt.Sprintf("%02d-%02d-%02d %02d:%02d:%02d",now.Year(),int(now.Month()),
							now.Day(),now.Hour(),now.Minute(),now.Second())
	//2020-03-18 19:25:07
	fmt.Printf("%s",dateStr1)
	fmt.Println()
	//格式化方式二:
	//2020/03/18 19:30:29
	fmt.Printf(now.Format("2006/01/02 15:04:05"))
	fmt.Println()
	//2020-03-18 19:30:29
	fmt.Printf(now.Format("2006-01-02 15:04:05"))
	fmt.Println()
	//2020-03-18
	fmt.Printf(now.Format("2006-01-02"))
	fmt.Println()
	//19:30:29
	fmt.Printf(now.Format("15:04:05"))


}

 

你可能感兴趣的:(golang)