Convertir l'horodatage en chaîne [dupliquer]

Dec 07 2020

Je veux obtenir un horodatage sous forme de chaîne. Si j'utilise la stringconversion, je n'ai aucune erreur mais la sortie n'est pas lisible. Plus tard, je le veux dans le cadre d'un nom de fichier. Cela ressemble à un point d'interrogation pour par exemple J'ai trouvé quelques exemples comme celui-ci:https://play.golang.org/p/bq2h3h0YKpne résout pas complètement mon problème. Merci

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

Comment pourrais-je obtenir l'horodatage sous forme de chaîne?

Réponses

2 Gealber Dec 07 2020 at 05:52

Quelque chose comme ça fonctionne pour moi

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

Voici deux exemples de la façon dont vous pouvez convertir un horodatage unix en chaîne.

Le premier exemple ( s1) utilise le strconvpackage et sa fonction FormatInt. Le deuxième exemple ( s2) utilise le fmtpackage ( documentation ) et sa fonction Sprintf.

Personnellement, j'aime Sprintfdavantage l' option d'un point de vue esthétique. Je n'ai pas encore vérifié les performances.

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)
}

Terrain de jeu Golang: https://play.golang.org/p/jk_xHYK_5Vu