KING 博主等级

一帆风顺 ⛵️⛵️⛵️

Go

golang Time日期格式化

钟晓川
2023-06-12 / 1 点赞 / 1091 阅读

在Go语言中,你可以使用time包中的函数和布局来进行日期和时间的格式化。下面是一些常用的日期格式化示例:

package main

import (
	"fmt"
	"time"
)

func main() {
	now := time.Now()

	// 格式化为字符串
  fmt.Println(now.Format("2006-01-02"))                 // 输出:2023-06-04
	fmt.Println(now.Format("2006-01-02 15:04:05"))        // 输出:2023-06-04 12:34:56
	fmt.Println(now.Format("2006/01/02 15:04:05 MST"))    // 输出:2023/06/04 12:34:56 UTC
	fmt.Println(now.Format("2006/01/02 15:04:05 -0700 MST"))  
  // 输出:2023/06/04 12:34:56 -0700 UTC
	fmt.Println(now.Format("Mon, Jan 2, 2006"))           // 输出:Sun, Jun 4, 2023
	fmt.Println(now.Format("Monday, January 2, 2006"))    // 输出:Sunday, June 4, 2023

	// 解析字符串为时间
	dateString := "2023-06-04 12:34:56"
	parsedTime, _ := time.Parse("2006-01-02 15:04:05", dateString)
	fmt.Println(parsedTime)  
  // 输出:2023-06-04 12:34:56 +0000 UTC
}

在格式化日期和时间时,需要使用特定的布局字符串,其中"2006-01-02"、"15:04:05"等是固定的占位符。这是由Go语言的时间包的设计所决定的。

你可以根据自己的需求调整布局字符串,详情请参阅Go语言官方文档中有关time包的内容:
https://golang.org/pkg/time/

1