-4

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?

2
  • 1
    The error shows the string representation of what you’re parsing, which obviously isn’t a number. string(a) isn’t going to format the number in a string, it’s converting it as ”\xef\xbf\xbd” Commented Jul 24, 2022 at 13:19
  • @JimB how to convert int64 into a number as is? Commented Jul 24, 2022 at 13:22

1 Answer 1

0

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 �

Sign up to request clarification or add additional context in comments.

2 Comments

you can also try it with strconv.Atoi(strconv.FormatInt(a, 10))
What'll be the difference?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.