タイムスタンプを文字列として変換[重複]

Dec 07 2020

タイムスタンプを文字列として取得したい。string変換を使用した場合、エラーは発生しませんが、出力が読み取れません。後で、ファイル名の一部として使用したいと思います。たとえば、疑問符のように見えます。次のような例がいくつか見つかりました。https://play.golang.org/p/bq2h3h0YKp私の問題を完全に解決するわけではありません。ありがとう

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

タイムスタンプを文字列として取得するにはどうすればよいですか?

回答

2 Gealber Dec 07 2020 at 05:52

このようなものは私のために働きます

package main

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

func main() {
    now := time.Now()
    unix := now.Unix()
    fmt.Println(strconv.FormatInt(unix, 10))
}
1 Jens Dec 07 2020 at 05:51

UNIXタイムスタンプを文字列に変換する方法の2つの例を次に示します。

最初の例(s1)は、strconvパッケージとその関数を使用していますFormatInt。2番目の例(s2)は、fmtパッケージ(ドキュメント)とその関数を使用していますSprintf

個人的にSprintfは、美的観点からこのオプションの方が好きです。まだ性能をチェックしていません。

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