타임 스탬프를 문자열로 변환 [중복]
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 타임 스탬프를 문자열로 변환하는 방법에 대한 두 가지 예입니다.
첫 번째 예 ( s1
)는 strconv
패키지와 그 기능을 사용합니다 FormatInt
. 두 번째 예제 ( 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 놀이터 : https://play.golang.org/p/jk_xHYK_5Vu