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 这些固定数字来代表对应的年、月、日、时、分、秒。

相关推荐
GreenTea2 小时前
GrokBot 核心成员 Lauren Tan:每月交付 2000 个 PR 的人,是怎么用 AI 的
前端·后端·架构
码事漫谈2 小时前
FDE:一个缩写,两种命运
后端
名字还没想好☜3 小时前
Go context.AfterFunc 实战(Go 1.21):context 一取消就自动跑清理,告别手写 goroutine 监听 Done
后端·golang·go
明月_清风4 小时前
为什么最近开始关注 JEV?几个实战案例告诉你答案
人工智能·后端
GetcharZp5 小时前
5 分钟拥有自己的 S3:RustFS 上手(MinIO 的 Rust 替代,Apache 2.0 可商用)
后端
行百里er5 小时前
Redis 版本演进、新特性与协议那些事儿
redis·后端
Joy T6 小时前
Spring AI 2.0 Agent 进阶:Memory、State 与 Context Engineering 常见技术全景
java·人工智能·后端·spring·agent入门·agent state
打工仔折腾 AI6 小时前
FastAPI 从本机到生产服务器:Nginx+Gunicorn+Uvicorn 完整部署实录
人工智能·后端·python·nginx·fastapi·gunicorn
IT_陈寒6 小时前
Java空指针这次真把我坑惨了
前端·人工智能·后端