Golang中将UTC日期格式转换为所需格式的方法

Golang中将UTC日期格式转换为所需格式的方法 需要转换存储在数据库中的UTC时区时间。类似这样 - 2020-02-21 10:29:42.812149 +0000 UTC 而我期望得到的是 - Fri, 21 Feb 2020 13:29:42 +03 我有一个函数,用于返回转换后的日期版本 -

var location, _ = time.LoadLocation("Europe/Minsk")

func convertToResponse(books Book) BookResponse {

	return BookResponse{
		ID:     books.ID,
		Name:   books.Name,
		Author: books.Author,
		Date:   books.Date.In(location).Format(time.RFC1123),
	}
}

我创建了一个从数据库中选择数据的端点,但当我运行它时,日期格式却是这样的 -

  {
        "id": 19,
        "name": "book19",
        "author": "QWERT",
        "date": "Sat, 01 Jan 0000 12:17:16 LMT"
    }

它没有被正确格式化。我不确定哪里出了问题。 这是完整代码的链接,如果你需要的话 -

GitHub GitHub

Avatar

JustinObanor/lets_Go

一系列用Go编写的任务。通过在GitHub上创建账户,为JustinObanor/lets_Go的开发做出贡献。


更多关于Golang中将UTC日期格式转换为所需格式的方法的实战教程也可以访问 https://www.itying.com/category-94-b0.html

8 回复

仅以UTC格式显示日期

更多关于Golang中将UTC日期格式转换为所需格式的方法的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


books.Date 的确切值是什么?books.Date.In(location) 的值又是什么?

如果你去掉对 In 的调用,它会显示正确的 UTC 时间吗?

我正在将 time.Now().UTC() 插入到数据库的日期字段中,并且“应该”得到这种格式的响应:books.Date.In(location).Format(time.RFC1123)

你可以从官方的 time 包或以下内容获取帮助:

图片

Go 日期和时间格式化 - GolangLearn

图片

在本教程中,我将向你介绍使用 Go 语言 time 包处理日期时间的一些基本格式。Go 提供了 time 包,其中包含一些便捷的功能。

books.Date 的值是 -

0000-01-01 10:27:00.138572 +0000 UTC

这只是UTC时区的日期。原始格式。

Need to convert the UTC time zones I stored in my database. Something like this -

2020-02-21 10:29:42.812149 +0000 UTC

需要转换我存储在数据库中的UTC时区。类似这样 -

2020-02-21 10:29:42.812149 +0000 UTC

books.Date.In(location) 的值应该是将UTC时区转换为我期望的所需位置的格式。

and what I expect to get us -

Fri, 21 Feb 2020 13:29:42 +03

而我期望得到的是 -

Fri, 21 Feb 2020 13:29:42 +03

也许这个资源会有所帮助

stackoverflow.com

peterSO

在 Go 中将 UTC 转换为“本地”时间

标签: time, go, timezone, timezone-offset

peterSO11:52PM - 14 Aug 14 UTC 回答

问题在于数据库中的时间字段解析不正确。从错误输出 Sat, 01 Jan 0000 12:17:16 LMT 可以看出,books.Date 字段被解析成了零值时间,而不是数据库中的实际时间。

需要确保数据库中的时间字段被正确解析为 time.Time 类型。以下是修正后的代码示例:

package main

import (
    "database/sql"
    "time"
)

var location, _ = time.LoadLocation("Europe/Minsk")

// 假设数据库字段是 timestamp 或 datetime 类型
type Book struct {
    ID   int
    Name string
    Author string
    Date time.Time
}

type BookResponse struct {
    ID     int    `json:"id"`
    Name   string `json:"name"`
    Author string `json:"author"`
    Date   string `json:"date"`
}

func convertToResponse(book Book) BookResponse {
    // 确保时区转换和格式化
    formattedDate := book.Date.In(location).Format("Mon, 02 Jan 2006 15:04:05 -07")
    
    return BookResponse{
        ID:     book.ID,
        Name:   book.Name,
        Author: book.Author,
        Date:   formattedDate,
    }
}

// 数据库查询示例
func getBookFromDB(db *sql.DB, id int) (Book, error) {
    var book Book
    // 明确指定扫描时的列名
    err := db.QueryRow("SELECT id, name, author, date FROM books WHERE id = ?", id).
        Scan(&book.ID, &book.Name, &book.Author, &book.Date)
    if err != nil {
        return Book{}, err
    }
    return book, nil
}

如果数据库存储的是字符串格式的时间,需要先解析:

func parseDBTime(dateStr string) (time.Time, error) {
    // 根据数据库实际格式调整布局字符串
    layouts := []string{
        "2006-01-02 15:04:05.999999 -0700 UTC",
        "2006-01-02 15:04:05.999999",
        time.RFC3339,
    }
    
    for _, layout := range layouts {
        t, err := time.Parse(layout, dateStr)
        if err == nil {
            return t, nil
        }
    }
    return time.Time{}, fmt.Errorf("无法解析时间: %s", dateStr)
}

检查数据库连接和扫描代码,确保时间字段被正确读取。如果使用GORM,确保模型定义正确:

type Book struct {
    ID     uint      `gorm:"primaryKey"`
    Name   string
    Author string
    Date   time.Time
}

时区转换和格式化部分是正确的,主要问题在于时间数据的读取阶段。

回到顶部