-2

I want to get a timestamp as string. If I use string conversion I got no error but the output is not readable. Later, I want us it as a part of a filename. It looks like a question mark for e.g. � I found some examples like this: https://play.golang.org/p/bq2h3h0YKp not solves completely me problem. thanks

now := time.Now()      // current local time
sec := now.Unix()      // number of seconds since January 1, 1970 UTC
fmt.Println(string(sec))

How could I get the timestamp as string?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
SL5net
  • 2,282
  • 4
  • 28
  • 44

2 Answers2

3

Something like this works for me

package main

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

func main() {
    now := time.Now()
    unix := now.Unix()
    fmt.Println(strconv.FormatInt(unix, 10))
}
Gealber
  • 463
  • 5
  • 13
  • that helps me to search next step. for my filenames i now use: `var re = regexp.MustCompile(`[\W]+`) s3 := re.ReplaceAllString(time.Now().Format(time.RFC3339), `-`)` – SL5net Dec 06 '20 at 23:13
1

Here are two examples of how you can convert a unix timestamp to a string.

The first example (s1) uses the strconv package and its function FormatInt. The second example (s2) uses the fmt package (documentation) and its function Sprintf.

Personally, I like the Sprintf option more from an aesthetic point of view. I did not check the performance yet.

package main

import "fmt"
import "time"
import "strconv"

func main() {
    t := time.Now().Unix() // t is of type int64
    
    // use strconv and FormatInt with base 10 to convert the int64 to string
    s1 := strconv.FormatInt(t, 10)
    fmt.Println(s1)
    
    // Use Sprintf to create a string with format:
    s2 := fmt.Sprintf("%d", t)
    fmt.Println(s2)
}

Golang Playground: https://play.golang.org/p/jk_xHYK_5Vu

Jens
  • 20,533
  • 11
  • 60
  • 86