GORM PostgreSQL获取不带时区的日期列

huangapple go评论72阅读模式
英文:

GORM PostgreSQL getting date column without timezone

问题

我正在学习golang,目前正在使用gorm尝试选择查询获取日期列,但它一直返回'2020-01-10T00:00:00Z',我该如何去掉时区?
我尝试将日期更改为time.Time或字符串,但都没有起作用,以下是代码:

type Price struct {
	DateStay time.Time `json:"date"`
	Price    int       `json:"price"`
}

更新:
这是我正在使用的代码:

var price []models.Price
err = models.DB.Raw(`
	SELECT P.date_stay, P.price
	FROM prices p
	WHERE P.room_type_id = ?
`, roomTypeId).Scan(&price).Error

我尝试在查询中使用P.date_stay::date或date(P.date_stay),但都没有起作用。
我希望它返回'2020-01-10'。

英文:

I'm learning golang atm, and currently I'm using gorm trying to select query getting date column, but it keep returning '2020-01-10T00:00:00Z', how do I get rid of the timezone?
<br>
I've tried changing date to time.Time or string, nothing works, here is the code

type Price struct {
	DateStay time.Time `json:&quot;date&quot;`
	Price    int       `json:&quot;price&quot;`
}

Update: <br>
This is the code that I am using

		var price []models.Price
		err = models.DB.Raw(`
			SELECT P.date_stay, P.price
			FROM prices p
			WHERE P.room_type_id = ?
		`, roomTypeId).Scan(&amp;price).Error

I tried to P.date_stay::date, date(P.date_stay) on the query but nothing works
<br>
I expect it to return '2020-01-10'

答案1

得分: 4

使用time.Time作为日期类型可能是最好的选择。

您可以通过将格式设置为所需的日期格式来格式化日期的结果(例如dd-mm-yyyy或任何您喜欢的顺序)。

然后,您可以使用time.Parse(format, date)来格式化值。

假设price是您的选择查询的结果。

如果您的时间是time.Time类型,您可以尝试使用price.DateStay.Format(format)

英文:

Using time.Time as a type for the date is probably best.

You can format the result of the date by setting the format to the desired date format you want.
(dd-mm-yyyy or whatever order you please).

Then you can format the value using time.Parse(format, date)

format := &quot;2000-01-13&quot;
formattedDate, err := time.Parse(format, price.DateStay)

assuming price is a result from your select query.

If you time is a time.Time you can try using price.DateStay.Format(format)

huangapple
  • 本文由 发表于 2022年2月27日 13:05:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/71282244.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定