目录
- 基本时间操作
- 特定日期时间格式
- 自定义日期时间格式
- 解析不同格式的日期时间字符串
- 获取指定日期时间
基本时间操作
首先,我们来看一些基本的时间操作。
获取当前时间可以使用time.Now()
函数,它会返回当前的时间对象,类型为time.Time
。以下是一个示例:
package main import ( "fmt" "time" ) func main() { currentTime := time.Now() fmt.Println("Current time is", currentTime) }
输出结果类似于:
Current time is 2022-05-24 11:07:36.710239 +0800 CST m=+0.000149139
这里的格式是默认的,如果我们想要按照特定的格式来输出时间,需要使用time.Format()
函数
package main import ( "fmt" "time" ) func main() { currentTime := time.Now() fmt.Println("Current time is", currentTime.Format("2006-01-02 15:04:05")) }
输出结果类似于:
Current time is 2022-05-24 11:08:11
这里使用了一个特殊的日期格式字符串"2006-01-02 15:04:05"
,它的含义是:
- 2006 表示年份
- 01 表示月份
- 02 表示日期
- 15 表示小时
- 04 表示分钟
- 05 表示秒钟
需要注意的是,格式字符串中的数字必须是这些特定的数字,否则会出现错误。
我们也可以使用time.Parse()
函数将一个字符串转化为time.Time
对象。
package main import ( "fmt" "time" ) func main() { timeStr := "2022-05-24 11:08:11" parsedTime, _ := time.Parse("2006-01-02 15:04:05", timeStr) fmt.Println("Parsed time is", parsedTime) }
输出结果类似于:
Parsed time is 2023-05-24 11:08:11 +0000 UTC
特定日期时间格式
在上面的示例中,我们使用了一个特定的日期格式字符串。下面列举一些常用的特定日期时间格式:
2006-01-02
:日期,如 2023-05-2415:04:05
:时间,如 11:08:112006-01-02 15:04:05
:日期时间,如 2023-05-24 11:08:1101/02/06 3:04 PM
:美国日期时间格式,如 05/24/22 11:08 AM02/01/2006 15:04
:欧洲日期时间格式,如 24/05/2022 11:08
除了上面的格式外,Golang还提供了更丰富的特定日期时间格式,请参考官方文档了解更多信息。
自定义日期时间格式
如果上面提供的特定日期时间格式无法满足我们的需求,我们可以自定义日期时间格式。
package main import ( "fmt" "time" ) func main() { currentTime := time.Now() customFormat := "2006年01月02日 15点04分05秒" fmt.Println("Current time is", currentTime.Format(customFormat)) }
输出结果类似于
Current time is 2023年05月24日 11点14分53秒
解析不同格式的日期时间字符串
有时候我们会遇到各种各样的日期时间字符串格式,这时我们需要能够正确地解析它们
package main import ( "fmt" "time" ) func main() { timeStr := "2023-05-24 11:08:11" parsedTime, _ := time.Parse("2006-01-02 15:04:05", timeStr) fmt.Println("Parsed time is", parsedTime) timeStr2 := "05/24/22 11:08 AM" parsedTime2, _ := time.Parse("01/02/06 3:04 PM", timeStr2) fmt.Println("Parsed time is", parsedTime2) timeStr3 := "2023年05月24日 11点14分53秒" parsedTime3, _ := time.Parse("2006年01月02日 15点04分05秒", timeStr3) fmt.Println("Parsed time is", parsedTime3) }
获取指定日期时间
有时候我们需要获取指定的日期时间,可以使用time.Date()
函数。
package main import ( "fmt" "time" ) func main() { specTime := time.Date(2023, 5, 24, 12, 0, 0, 0, time.Local) fmt.Println("Specified time is", specTime.Format("2006-01-02 15:04:05")) }
输出结果类似于:
Specified time is 2022-05-24 12:00:00
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
评论(0)