将time.Time转换为字符串。

huangapple go评论88阅读模式
英文:

Convert time.Time to string

问题

我正在尝试将数据库中的一些值添加到Go语言中的[]string中。其中一些值是时间戳。

我遇到了以下错误:

> cannot use U.Created_date (type time.Time) as type string in array element

我能将time.Time转换为string吗?

type UsersSession struct {
    Userid int
    Timestamp time.Time
    Created_date time.Time
}

type Users struct {
    Name string
    Email string
    Country string
    Created_date time.Time
    Id int
    Hash string
    IP string
}

var usersArray = [][]string{}

rows, err := db.Query("SELECT u.id, u.hash, u.name, u.email, u.country, u.IP, u.created_date, us.timestamp, us.created_date FROM usersSession AS us LEFT JOIN users AS u ON u.id = us.userid WHERE us.timestamp + interval 30 minute >= now()")

U := Users{}
US := UsersSession{}

for rows.Next() {
    err = rows.Scan(&U.Id, &U.Hash, &U.Name, &U.Email, &U.Country, &U.IP, &U.Created_date, &US.Timestamp, &US.Created_date)
    checkErr(err)

    userid_string := strconv.Itoa(U.Id)
    user := []string{userid_string, U.Hash, U.Name, U.Email, U.Country, U.IP, U.Created_date, US.Timestamp, US.Created_date}
    // -------------
    // ^ 这是出错的地方
    // 无法将U.Created_date(类型为time.Time)用作数组元素中的string类型(对于US.Created_date和US.Timestamp也是如此)
    // -------------

    usersArray = append(usersArray, user)
    log.Print("usersArray: ", usersArray)
}

编辑

我添加了以下内容。现在它可以工作了,谢谢。

userCreatedDate := U.Created_date.Format("2006-01-02 15:04:05")
userSessionCreatedDate := US.Created_date.Format("2006-01-02 15:04:05")
userSessionTimestamp := US.Timestamp.Format("2006-01-02 15:04:05")
英文:

I'm trying to add some values from my database to a []string in Go. Some of these are timestamps.

I get the error:

> cannot use U.Created_date (type time.Time) as type string in array element

Can I convert time.Time to string?

type UsersSession struct {
    Userid int
    Timestamp time.Time
    Created_date time.Time
}

type Users struct {
    Name string
    Email string
    Country string
    Created_date time.Time
    Id int
    Hash string
    IP string
}

-

var usersArray = [][]string{}

rows, err := db.Query("SELECT u.id, u.hash, u.name, u.email, u.country, u.IP, u.created_date, us.timestamp, us.created_date FROM usersSession AS us LEFT JOIN users AS u ON u.id = us.userid WHERE us.timestamp + interval 30 minute >= now()")

U := Users{}
US := UsersSession{}

for rows.Next() {
    err = rows.Scan(&U.Id, &U.Hash, &U.Name, &U.Email, &U.Country, &U.IP, &U.Created_date, &US.Timestamp, &US.Created_date)
    checkErr(err)

    userid_string := strconv.Itoa(U.Id)
    user := []string{userid_string, U.Hash, U.Name, U.Email, U.Country, U.IP, U.Created_date, US.Timestamp, US.Created_date}
    // -------------
    // ^ this is where the error occurs
    // cannot use U.Created_date (type time.Time) as type string in array element (for US.Created_date and US.Timestamp aswell)
    // -------------

    usersArray = append(usersArray, user)
    log.Print("usersArray: ", usersArray)
}

EDIT

I added the following. It works now, thanks.

userCreatedDate := U.Created_date.Format("2006-01-02 15:04:05")
userSessionCreatedDate := US.Created_date.Format("2006-01-02 15:04:05")
userSessionTimestamp := US.Timestamp.Format("2006-01-02 15:04:05")

答案1

得分: 263

你可以使用Time.String()方法将time.Time转换为字符串。它使用格式字符串"2006-01-02 15:04:05.999999999 -0700 MST"

如果你需要其他自定义格式,可以使用Time.Format()。例如,要以yyyy-MM-dd HH:mm:ss的格式获取时间戳,可以使用格式字符串"2006-01-02 15:04:05"

示例:

t := time.Now()
fmt.Println(t.String())
fmt.Println(t.Format("2006-01-02 15:04:05"))

输出结果(在Go Playground上尝试):

2009-11-10 23:00:00 +0000 UTC
2009-11-10 23:00:00

注意:Go Playground上的时间始终设置为上述值。在本地运行以查看当前日期/时间。

还要注意,使用Time.Format()时,布局字符串始终需要传递相同的时间(称为“参考”时间),以所需的格式进行格式化。这在Time.Format()的文档中有说明:

> Format根据布局返回时间值的文本表示形式,布局定义了如何显示参考时间,参考时间定义为
>
> Mon Jan 2 15:04:05 -0700 MST 2006
>
> 如果它是该值,它将显示为所需的输出示例。然后,相同的显示规则将应用于时间值。

英文:

You can use the Time.String() method to convert a time.Time to a string. This uses the format string "2006-01-02 15:04:05.999999999 -0700 MST".

If you need other custom format, you can use Time.Format(). For example to get the timestamp in the format of yyyy-MM-dd HH:mm:ss use the format string "2006-01-02 15:04:05".

Example:

t := time.Now()
fmt.Println(t.String())
fmt.Println(t.Format("2006-01-02 15:04:05"))

Output (try it on the Go Playground):

2009-11-10 23:00:00 +0000 UTC
2009-11-10 23:00:00

Note: time on the Go Playground is always set to the value seen above. Run it locally to see current date/time.

Also note that using Time.Format(), as the layout string you always have to pass the same time –called the reference time– formatted in a way you want the result to be formatted. This is documented at Time.Format():

> Format returns a textual representation of the time value formatted according to layout, which defines the format by showing how the reference time, defined to be
>
> Mon Jan 2 15:04:05 -0700 MST 2006
>
> would be displayed if it were the value; it serves as an example of the desired output. The same display rules will then be applied to the time value.

答案2

得分: 32

package main

import (
    "fmt"
    "time"
)

// @link https://golang.org/pkg/time/

func main() {

    //注意:格式字符串为`2006-01-02 15:04:05.000000000`
    current := time.Now()

    fmt.Println("原始时间:", current.String())
    // 原始时间: 2016-09-02 15:53:07.159994437 +0800 CST

    fmt.Println("月-日-年:", current.Format("01-02-2006"))
    // 月-日-年: 09-02-2016

    fmt.Println("年-月-日:", current.Format("2006-01-02"))
    // 年-月-日: 2016-09-02

    // 用.分隔
    fmt.Println("年.月.日:", current.Format("2006.01.02"))
    // 年.月.日: 2016.09.02

    fmt.Println("年-月-日 时:分:秒:", current.Format("2006-01-02 15:04:05"))
    // 年-月-日 时:分:秒: 2016-09-02 15:53:07

    // StampMicro
    fmt.Println("年-月-日 时:分:秒:", current.Format("2006-01-02 15:04:05.000000"))
    // 年-月-日 时:分:秒: 2016-09-02 15:53:07.159994

    //StampNano
    fmt.Println("年-月-日 时:分:秒:", current.Format("2006-01-02 15:04:05.000000000"))
    // 年-月-日 时:分:秒: 2016-09-02 15:53:07.159994437
}

以上是一个Go语言程序,用于演示时间格式化的不同方式。它将当前时间按照不同的格式进行输出。

英文:
package main                                                                                                                                                           

import (
    "fmt"
    "time"
)

// @link https://golang.org/pkg/time/

func main() {

    //caution : format string is `2006-01-02 15:04:05.000000000`
    current := time.Now()

    fmt.Println("origin : ", current.String())
    // origin :  2016-09-02 15:53:07.159994437 +0800 CST

    fmt.Println("mm-dd-yyyy : ", current.Format("01-02-2006"))
    // mm-dd-yyyy :  09-02-2016

    fmt.Println("yyyy-mm-dd : ", current.Format("2006-01-02"))
    // yyyy-mm-dd :  2016-09-02

    // separated by .
    fmt.Println("yyyy.mm.dd : ", current.Format("2006.01.02"))
    // yyyy.mm.dd :  2016.09.02

    fmt.Println("yyyy-mm-dd HH:mm:ss : ", current.Format("2006-01-02 15:04:05"))
    // yyyy-mm-dd HH:mm:ss :  2016-09-02 15:53:07

    // StampMicro
    fmt.Println("yyyy-mm-dd HH:mm:ss: ", current.Format("2006-01-02 15:04:05.000000"))
    // yyyy-mm-dd HH:mm:ss:  2016-09-02 15:53:07.159994

    //StampNano
    fmt.Println("yyyy-mm-dd HH:mm:ss: ", current.Format("2006-01-02 15:04:05.000000000"))
    // yyyy-mm-dd HH:mm:ss:  2016-09-02 15:53:07.159994437
}    

答案3

得分: 10

package main

import (
	"fmt"
	"time"
)

func main() {
	v, _ := time.Now().UTC().MarshalText()
	fmt.Println(string(v))
}

输出:2009-11-10T23:00:00Z

Go Playground

英文:
package main

import (
	"fmt"
	"time"
)

func main() {
	v , _ := time.Now().UTC().MarshalText()
	fmt.Println(string(v))
}

Output : 2009-11-10T23:00:00Z

Go Playground

答案4

得分: 3

请找到在Go语言中转换日期和时间格式的简单解决方案。请参考以下示例。

包链接:https://github.com/vigneshuvi/GoDateFormat

请查看占位符:https://medium.com/@Martynas/formatting-date-and-time-in-golang-5816112bf098

package main

// 导入包
import (
    "fmt"
    "time"
    "github.com/vigneshuvi/GoDateFormat"
)

func main() {
    fmt.Println("Go日期格式(今天 - 'yyyy-MM-dd HH:mm:ss Z'):", GetToday(GoDateFormat.ConvertFormat("yyyy-MM-dd HH:mm:ss Z")))
    fmt.Println("Go日期格式(今天 - 'yyyy-MMM-dd'):", GetToday(GoDateFormat.ConvertFormat("yyyy-MMM-dd")))
    fmt.Println("Go时间格式(现在 - 'HH:MM:SS'):", GetToday(GoDateFormat.ConvertFormat("HH:MM:SS")))
    fmt.Println("Go时间格式(现在 - 'HH:MM:SS tt'):", GetToday(GoDateFormat.ConvertFormat("HH:MM:SS tt")))
}

func GetToday(format string) (todayString string){
    today := time.Now()
    todayString = today.Format(format);
    return
}

[1]: https://github.com/vigneshuvi/GoDateFormat
[2]: https://medium.com/@Martynas/formatting-date-and-time-in-golang-5816112bf098

以上是代码的翻译部分。

英文:

Please find the simple solution to convete Date & Time Format in Go Lang. Please find the example below.

Package Link: https://github.com/vigneshuvi/GoDateFormat.

Please find the plackholders:https://medium.com/@Martynas/formatting-date-and-time-in-golang-5816112bf098

package main


// Import Package
import (
    "fmt"
    "time"
    "github.com/vigneshuvi/GoDateFormat"
)

func main() {
    fmt.Println("Go Date Format(Today - 'yyyy-MM-dd HH:mm:ss Z'): ", GetToday(GoDateFormat.ConvertFormat("yyyy-MM-dd HH:mm:ss Z")))
    fmt.Println("Go Date Format(Today - 'yyyy-MMM-dd'): ", GetToday(GoDateFormat.ConvertFormat("yyyy-MMM-dd")))
    fmt.Println("Go Time Format(NOW - 'HH:MM:SS'): ", GetToday(GoDateFormat.ConvertFormat("HH:MM:SS")))
    fmt.Println("Go Time Format(NOW - 'HH:MM:SS tt'): ", GetToday(GoDateFormat.ConvertFormat("HH:MM:SS tt")))
}

func GetToday(format string) (todayString string){
    today := time.Now()
    todayString = today.Format(format);
    return
}

答案5

得分: 3

strconv.Itoa(int(time.Now().Unix()))

将当前时间转换为整数并转换为字符串。

英文:
strconv.Itoa(int(time.Now().Unix()))

答案6

得分: 2

Go Playground
http://play.golang.org/p/DN5Py5MxaB

package main

import (
    "fmt"
    "time"
)

func main() {
    t := time.Now()
    // Time 类型实现了 Stringer 接口 -- 它有一个 String() 方法,会被像 Printf() 这样的函数自动调用。
    fmt.Printf("%s\n", t)
    
    // 更多格式请参考 Constants 部分
    // http://golang.org/pkg/time/#Time.Format
    formatedTime := t.Format(time.RFC1123)
    fmt.Println(formatedTime)
}
英文:

Go Playground
http://play.golang.org/p/DN5Py5MxaB

package main

import (
    "fmt"
    "time"
)

func main() {
    t := time.Now()
	// The Time type implements the Stringer interface -- it
    // has a String() method which gets called automatically by
    // functions like Printf().
    fmt.Printf("%s\n", t)
    
    // See the Constants section for more formats
    // http://golang.org/pkg/time/#Time.Format
    formatedTime := t.Format(time.RFC1123)
    fmt.Println(formatedTime)
}

huangapple
  • 本文由 发表于 2015年10月14日 15:57:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/33119748.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定