go格式化时间

前言

在使用go开发中,有时候需要格式化时间,go语言的格式化时间有点特殊,使用2006-01-02 15:04:05

go格式化时间

格式化时间

go 复制代码
package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    a := now.Format("2006-01-02 15:04:05")
    fmt.Println(a)
}

输出结果为

go 复制代码
package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    a := now.Format("2006-01-02")
    fmt.Println(a)
}

输出结果为

go 复制代码
package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now() 
    a := now.Format("15:04:05")
    fmt.Println(a)
}

输出结果为

可以使用中文

go 复制代码
package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    a := now.Format("2006年01月02日 15时04分05秒")
    fmt.Println(a)
}

输出结果为

12小时制和AM/PM

go 复制代码
package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    a := now.Format("2006-01-02 03:04:05 PM")
    fmt.Println(a)
}

输出结果为

毫秒、微秒、纳秒

go 复制代码
package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    a := now.Format("2006-01-02 03:04:05.000")
    fmt.Println(a)
}

输出结果为

总结

time.Format() 方法的参数不是一个"模式字符串",而是一个具体的日期时间示例 。你必须使用 20060102150405 这些固定数字来代表对应的年、月、日、时、分、秒。

相关推荐
IT_陈寒2 小时前
Vite的热更新突然不香了,排查三小时差点砸键盘
前端·人工智能·后端
子兮曰2 小时前
Agency-Agents 深度解析:400+ AI 专家的"梦之队"如何重塑开发工作流
前端·后端·vibecoding
用户8356290780513 小时前
Python 实现 PDF 文件加密与解密方法
后端·python
小满zs3 小时前
Go语言第二章(小无相功)
后端·go
用户8356290780513 小时前
使用 Python 冻结与拆分 Excel 窗格教程
后端·python
karry_k3 小时前
MyBatis批量insert-select踩坑:useGeneratedKeys=true 可能让PostgreSQL返回大量插入结果
java·后端
妙码生花3 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(十九):点选验证码代码逐行目检
前端·后端·go
老鹰8623 小时前
Google Wire 被官方抛弃,Uber Fx 启动就 panic,Go DI 还有救吗?
go
贰先生3 小时前
Xiuno BBS X版 用户封禁系统
后端
karry_k3 小时前
PostgreSQL 在 MyBatis 中执行正常 SQL 失效:一次 DELETE USING 踩坑记录
java·后端