Search This Blog

Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Friday, April 5, 2019

Convert string <-> int64 using golang #go-nuts

I believe that if you are going to work with timestamps is better to do it in epoch stamps, so in GO epoch is type int64.

package main

import (
    "fmt"
    "time"
    "strconv"
)

func main() {

    now := time.Now()
    nanos := now.UnixNano()
    bufferTimestamp := strconv.FormatInt(nanos, 10)

    fmt.Printf("bufferTimestamp value: %s\n", bufferTimestamp)
    timestamp, err := strconv.ParseInt(string(bufferTimestamp), 10, 64)
    if err != nil {
        fmt.Printf("Error: %d of type %T\n", timestamp, timestamp)
        panic(err)
    } else {
        fmt.Printf("Converted value: %d\n", timestamp)
    }
}

By running this you will have an output like this.

$ go run test/convert_stringtoint64.go 
bufferTimestamp value 1556951794912716618 of type string
Converted value 1556951794912716618 of type int64