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() 方法的参数不是一个"模式字符串",而是一个具体的日期时间示例 。你必须使用 2006、01、02、15、04、05 这些固定数字来代表对应的年、月、日、时、分、秒。

相关推荐
用户69371750013842 小时前
2026,程序员的时代拐点到了
android·前端·后端
惜鸟2 小时前
从源码看 pi 的上下文管理:原始数据永久保留,模型视角按需裁剪
后端
量化分析码农2 小时前
【Python量化策略评估体系 #05】极端行情扛得住吗?2008/2015/2020 三场景压力测试
后端
十年Java程序媛2 小时前
Java 接口和抽象类对比|Java8 新特性,抛弃老旧八股,正确选型
java·spring boot·后端
IT_陈寒2 小时前
SpringBoot自动配置差点让我加班到凌晨
前端·人工智能·后端
用户8356290780512 小时前
使用 Python 对 Excel 工作表进行排序
后端·python
程序员cxuan2 小时前
腾讯又来一王炸,开源版 WorkBuddy 太夯了!
人工智能·后端·程序员
用户8356290780513 小时前
使用 Python 合并 PowerPoint 演示文稿
后端·python
掘金者阿豪3 小时前
数据同步软件技术实践:从异构数据库迁移到实时数据流转,解析电科金仓KFS架构设计
后端
ServBay3 小时前
不会写代码,如何搭建自己的 AI 自动化工作流
后端·aigc·ai编程