【问题标题】:Convert timestamp as string [duplicate]将时间戳转换为字符串[重复]
【发布时间】:2020-12-06 22:34:58
【问题描述】:

我想得到一个时间戳作为字符串。如果我使用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))

如何将时间戳作为字符串获取?

【问题讨论】:

  • 您想以秒还是以特定格式打印?喜欢January 1, 1970
  • 几秒钟对我来说已经足够了。我通常使用 yyyy-mm-dd-hh-mm-ss 那最适合我

标签: go


【解决方案1】:

这样的东西对我有用

package main

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

func main() {
    now := time.Now()
    unix := now.Unix()
    fmt.Println(strconv.FormatInt(unix, 10))
}

【讨论】:

  • 这有助于我搜索下一步。对于我现在使用的文件名:var re = regexp.MustCompile([\W]+) s3 := re.ReplaceAllString(time.Now().Format(time.RFC3339), -)
【解决方案2】:

以下是如何将 unix 时间戳转换为字符串的两个示例。

第一个示例 (s1) 使用 strconv 包及其函数 FormatInt。第二个示例 (s2) 使用 fmt 包 (documentation) 及其函数 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

【讨论】:

    猜你喜欢
    • 2016-11-27
    • 2019-10-29
    • 2013-10-21
    • 2012-05-16
    • 1970-01-01
    • 2012-02-15
    • 2017-01-18
    • 2020-11-22
    • 1970-01-01
    相关资源
    最近更新 更多