string 将 time.Time 转换为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33119748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:27:30  来源:igfitidea点击:

Convert time.Time to string

stringtimego

提问by A.D

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

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

I get the error:

我收到错误:

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

不能使用 U.Created_date (type time.Time) 作为数组元素中的类型字符串

Can I convert time.Timeto string?

我可以转换time.Timestring吗?

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

回答by icza

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

您可以使用该Time.String()方法将 a 转换time.Time为 a 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:ssuse the format string "2006-01-02 15:04:05".

如果您需要其他自定义格式,您可以使用Time.Format(). 例如,以yyyy-MM-dd HH:mm:ss使用格式字符串的格式获取时间戳"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):

输出(在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.

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

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

另请注意,使用Time.Format(), 作为布局,string您始终必须传递相同的时间 - 称为参考时间 - 以您希望格式化结果的方式进行格式化。这是记录在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.

Format 返回根据布局格式化的时间值的文本表示,它通过显示如何定义参考时间来定义格式,定义为

Mon Jan 2 15:04:05 -0700 MST 2006

如果是值就会显示;它用作所需输出的示例。然后将相同的显示规则应用于时间值。

回答by Hao

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
}    

回答by Vignesh Kumar

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

请找到在 Go Lang 中讨论日期和时间格式的简单解决方案。请在下面找到示例。

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

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

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

请找到支持者: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
}

回答by firebitsbr

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

去游乐场 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)
}