我试图在Go中将一些值从我的数据库添加到[]字符串.其中有些是时间戳.
我得到错误:
cannot use U.Created_date (type time.Time) as type string in array element
可以将time.Time转换成字符串吗?
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) }
编辑
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")
您可以使用
原文链接:https://www.f2er.com/go/186994.htmlTime.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游乐场上的时间总是设置为上述值.在本地运行以查看当前日期/时间.
另请注意,使用Time.Format()作为布局字符串,您始终必须通过相同的时间 – 以您希望格式化结果的方式将参考时间格式化.这是在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
06002
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.