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

相关推荐
啊汉8 小时前
古文观芷App搜索方案深度解析:打造极致性能的古文搜索引擎
go·软件随想
一点程序10 小时前
基于SpringBoot的选课调查系统
java·spring boot·后端·选课调查系统
怪兽源码12 小时前
基于SpringBoot的选课调查系统
java·spring boot·后端·选课调查系统
csdn_aspnet12 小时前
ASP.NET Core 中的依赖注入
后端·asp.net·di·.net core
昊坤说不出的梦13 小时前
【实战】监控上下文切换及其优化方案
java·后端
疯狂踩坑人13 小时前
【Python版 2026 从零学Langchain 1.x】(二)结构化输出和工具调用
后端·python·langchain
橘子师兄15 小时前
C++AI大模型接入SDK—ChatSDK封装
开发语言·c++·人工智能·后端
@ chen15 小时前
Spring事务 核心知识
java·后端·spring
一点技术16 小时前
基于SpringBoot的选课调查系统
java·spring boot·后端·选课调查系统
RANCE_atttackkk17 小时前
Springboot+langchain4j的RAG检索增强生成
java·开发语言·spring boot·后端·spring·ai·ai编程