-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?

Kum
  • 45
  • 1
  • 7
  • 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”` – JimB Jul 24 '22 at 13:19
  • @JimB how to convert int64 into a number as is? – Kum Jul 24 '22 at 13:22

1 Answers1

-1

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 �

Anandu Reghu
  • 50
  • 1
  • 4