我有一个 JSON 响应,它返回 created
字段的 UNIX 时间戳值:
"created_utc": 1395800038.0
---
// The type I use to marshal the response JSON.
// I can't use string because Golang complains the JSON is a float.
type Submission struct {
CreatedUtc float32 `json:"created_utc"`
}
我想将其转换为实际的 Time
对象:
const longForm = "Jan 2, 2006 at 3:04pm (MST)"
created_at, _ := time.Parse(longForm, string(created_utc))
./main.go:57: cannot convert created_utc (type float32) to type string
所以我有点被困在这里了。我可以强制编码代码将时间戳转换为字符串,或者我可以在 time.Parse
代码中将浮点值转换为字符串 - 但如果没有 Golang,我似乎做不到提示。
最佳答案
您的代码有一些问题:
使用 float32 作为 Unix 时间戳
正如 Nick Craig-Wood 已经指出的那样,float32 无法在不损失精度的情况下存储 Unix 时间戳。虽然 JSON 标准不限制数字的精度,但 Javascript 将它们限制为 IEEE 754 64 位浮点值。
也就是说,最好将 JSON 数字存储在 float64 变量中以避免精度下降,除非您确定该数字适合 int(无小数)或 float32 或其他格式。
将 float64 转换为字符串以获取时间?
将 float 转换为字符串听起来像:
1395800038.0 => "1395800038.0"
我假设这不是您的意图,而是希望获得以下其中一项:
var t time.Time = time.Unix(1395800038, 0)
var s string = "2014 年 3 月 26 日凌晨 2:13(UTC)"//或任何其他格式
即使您的目标是获取字符串 (2),您仍然需要创建 time.Time 变量 (1)。所以它会分两步发生。
解决方案:
package main
import (
"encoding/json"
"fmt"
"time"
)
var data = []byte(`{"created_utc": 1395800038.0}`)
type Submission struct {
CreatedUtc float64 `json:"created_utc"`
}
func main() {
var sub Submission
err := json.Unmarshal(data, &sub)
if err != nil {
panic(err)
}
// First step, convert float64 to a time.Time (after a quick conversion to int64 as well)
dt := time.Unix(int64(sub.CreatedUtc), 0)
// Second step, convert the timestamp to a string representation of your choice
fmt.Println(dt.Format("2006-01-02 15:04:05"))
}
结果:
2014-03-26 02:13:58
Playground : http://play.golang.org/p/jNwzwc4dLg
关于json - 无法将 float32 值解码为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23326908/