惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
The GitHub Blog
The GitHub Blog
J
Java Code Geeks
Engineering at Meta
Engineering at Meta
N
Netflix TechBlog - Medium
A
About on SuperTechFans
博客园 - 三生石上(FineUI控件)
罗磊的独立博客
MongoDB | Blog
MongoDB | Blog
B
Blog RSS Feed
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
有赞技术团队
有赞技术团队
T
Tailwind CSS Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
Vercel News
Vercel News
腾讯CDC
博客园 - 聂微东
The Cloudflare Blog
F
Fortinet All Blogs
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
V
Visual Studio Blog
Last Week in AI
Last Week in AI
B
Blog

Time on 轻风云

暂无文章

golang中time.RFC3339时间格式化
2022-10-27 · via Time on 轻风云

在开发过程中,我们有时会遇到这样的问题,将 2022-10-22T08:18:46+08:00 转成 2022-10-22 08:18:46,怎么解决这个问题?

解决这个问题,最好不要用字符串截取,或者说字符串截取是最笨的方法,这应该是时间格式化的问题。

我们先看一下 golang time 包中支持的 format 格式:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
const (
    ANSIC       = "Mon Jan _2 15:04:05 2006"
    UnixDate    = "Mon Jan _2 15:04:05 MST 2006"
    RubyDate    = "Mon Jan 02 15:04:05 -0700 2006"
    RFC822      = "02 Jan 06 15:04 MST"
    RFC822Z     = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone
    RFC850      = "Monday, 02-Jan-06 15:04:05 MST"
    RFC1123     = "Mon, 02 Jan 2006 15:04:05 MST"
    RFC1123Z    = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone
    RFC3339     = "2006-01-02T15:04:05Z07:00"
    RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
    Kitchen     = "3:04PM"
    // Handy time stamps.
    Stamp      = "Jan _2 15:04:05"
    StampMilli = "Jan _2 15:04:05.000"
    StampMicro = "Jan _2 15:04:05.000000"
    StampNano  = "Jan _2 15:04:05.000000000"
)

我们找到了 RFC3339 ,那就很简单了,我们封装一个方法 RFC3339ToDateTime,见下面代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package lib

import "time"

var _ Time = (*timer)(nil)

const cstLayout = "2006-01-02 15:04:05"

type Time interface {
    RFC3339ToDateTime(value string) (string, error)
}

type timer struct {
    Cst *time.Location
}

func NewTime() Time {
    cst, _ := time.LoadLocation("Asia/Shanghai")
    return &timer{
        Cst: cst,
    }
}

func (con *timer) RFC3339ToDateTime(value string) (string, error) {
    ts, err := time.Parse(time.RFC3339, value)
    if err != nil {
        return "", err
    }
    return ts.In(con.Cst).Format(cstLayout), nil
}

运行一下

1
2
3
4
5
6
7
8
v, err := lib.NewTime().RFC3339ToDateTime("2022-10-22T08:18:46+08:00")
if err != nil {
    fmt.Println(err)
}
fmt.Println(v)

输出
2020-11-08 08:18:46

小结

同理,若遇到 RFC3339Nano、RFC822、RFC1123 等格式,也可以使用类似的方法,只需要在 time.Parse() 中指定时间格式即可。