回答

收藏

将 time.Time 转换为字符串

技术问答 技术问答 376 人阅读 | 0 人回复 | 2023-09-12

我试图在[]中添加我数据库中的一些值stringGo 中。有些是时间戳。
" K+ G5 X, R7 G& A我收到了错误:% d; D! Z, @, f1 g% J
不能使用 U.Created_date (type time.Time) 作为数组元素中的类型字符串- q( }/ s: i* }( C; f3 U" s
我可以转换time.Time为string吗?
0 p6 J! t: o# \0 g/ c9 O1 q) V
    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}+ Z6 U; \- B" ?4 t
——% x- U! I) |5 N3 b# q3 Q$ g
    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)}( ~! }7 r9 ]( W- ^) q
编辑; L' g% u/ t5 |' j  x+ D3 R
我添加了以下内容。现在可以用了,谢谢。: F8 g  g  h3 p, o) |- O
    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"); ]3 |- Z) p6 b4 V* [! c( z
               8 Z$ c% k8 s# Q" A$ E% \+ ^
    解决方案:                                                                . y6 o5 E5 ~/ g8 T0 G. L3 `' r
                                                                你可以用这个Time.String()方法将 a 转换time.Time为 a string。使用格式字符串"2006-01-02 15:04:05.999999999 -0700 MST"。) A) K- r% A+ E3 o3 _; j
如果需要其他自定义格式,可以使用Time.Format(). 例如,以yyyy-MM-dd HH:mm:ss使用格式字符串的格式获取时间戳"2006-01-02 15:04:05"。
1 e2 Z3 w. h/ }. B' s例子:
% W# Z" M) H) V# Z8 w3 q$ w
    t := time.Now()fmt.Println(t.String())fmt.Println(t.Format("2006-01-02 15:04:05")): f; v; Y7 z8 ]  K1 v
输出(在Go Playground上试试):
7 R# Z7 I) ~1 ]/ d6 X
    2009-11-10 23:00UTC2009-11-10 23:00:00
    0 A+ u* i% G# \% C: e' {8 H
注意:Go Playground 上述时间始终设置为上述值。在本地运行,查看当前日期/时间。
" x! f: O( O$ j3 g# I3 G) X& J请注意,使用Time.Format(),作为布局,string你必须一直传递同样的时间 - 称为参考时间 - 以你想要格式化结果的方式格式化。这是记录在内的Time.Format():* s7 z% c& ]- B+ v# ]' s$ Q& Z* B
Format 根据布局格式化的时间值,通过显示如何定义参考时间来定义格式
8 g+ X& o2 c% X& J: [& p$ m  ^golangMon Jan 2 15:04:05 -0700 MST 20062 y+ M0 y- ^1 I8 F3 H0 K3 e& o
如果是值,则会显示;它被用作所需输出的示例。然后在时间值中应用相同的显示规则。
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则