使用Golang打印特定的日期时间的操作
基本时间操作
首先,我们来看一些基本的时间操作。
获取当前时间可以使用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
到此这篇关于使用Golang打印特定的日期时间的操作的文章就介绍到这了,更多相关Golang打印特定的日期时间内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
golang gin ShouldBind的介绍和使用示例详解
在 Go 语言的 Gin 框架中,ShouldBind 是用于将请求中的数据绑定到结构体的一个方法,它简化了从请求中提取参数的过程,支持多种数据格式,下面给大家分享golang gin ShouldBind的介绍和使用示例,感兴趣的朋友一起看看吧2024-10-10
CentOS 32 bit安装golang 1.7的步骤详解
Go是Google开发的一种编译型,并发型,并具有垃圾回收功能的编程语言。在发布了6个rc版本之后,Go 1.7终于正式发布了。本文主要介绍了在CentOS 32 bit安装golang 1.7的步骤,文中给出了详细的步骤,相信对大家的学习和理解具有一定的参考借鉴价值,下面来一起看看吧。2016-12-12


最新评论