"panic: strconv.ParseInt: parsing "�": invalid syntax" –> when parting int64 to convert into time

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

"panic: strconv.ParseInt: parsing "�": invalid syntax" --> when parting int64 to convert into time

问题

在数据库中,我有一个类型为int64的字段,用于存储Unix时间戳。然后,我想将其作为普通的datetime字符串呈现给用户。然而,这会导致失败。以下是一个简单的示例。

package main

import (
	"fmt"
	"strconv"
)

func main() {
	var a int64
	a = 1658545089
	tm, err := strconv.ParseInt(string(a), 10, 64)
	if err != nil {
		panic(err)
	}

	fmt.Println(tm)
}

===>

panic: strconv.ParseInt: parsing "�": invalid syntax

这里发生了什么?

英文:

In a DB I have a field of type int64 in which I store unix timestamp. Then I want to present it to the user as a normal datetime, as a string. However, it'll fail. Here's a simple example.

package main

import (
	"fmt"
	"strconv"
)

func main() {
	var a int64
	a = 1658545089
	tm, err := strconv.ParseInt(string(a), 10, 64)
	if err != nil {
		panic(err)
	}

	fmt.Println(tm)
}

===>

panic: strconv.ParseInt: parsing "�": invalid syntax

What's going on here?

答案1

得分: -1

这是你要翻译的内容:

这是因为你试图将int64类型转换为字符串。
尝试使用strconv.FormatInt(a, 10)进行转换。

package main

import (
	"fmt"
	"strconv"
)

func main() {
	var a int64
	a = 1658545089
	tm, err := strconv.ParseInt(strconv.FormatInt(a, 10), 10, 64)
	if err != nil {
		panic(err)
	}

	fmt.Println(tm)
}

当你尝试将一个整数转换为字符串时,在Go语言中,它会得到相应的ASCII字符。
https://en.cppreference.com/w/cpp/language/ascii

在某个特定的整数之后,它只会显示�。

英文:

It is because you are trying to convert int64 with string
try it with strconv.FormatInt(a, 10)

package main

import (
	"fmt"
	"strconv"
)

func main() {
	var a int64
	a = 1658545089
	tm, err := strconv.ParseInt(strconv.FormatInt(a, 10), 10, 64)
	if err != nil {
		panic(err)
	}

	fmt.Println(tm)
}

when you try to convert an interger covering with string(), in golang it will get the corresponding ascii character
https://en.cppreference.com/w/cpp/language/ascii

after a certain interger it will only show �

huangapple
  • 本文由 发表于 2022年7月24日 21:06:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/73098662.html
匿名

发表评论

匿名网友

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

确定