In Go, you may encounter errors when trying to add time.Time timestamps directly to string arrays. To resolve this, you can convert time.Time values to strings using the String() or Format() method.
The String() method converts a time.Time to a string using the default format "2006-01-02 15:04:05.999999999 -0700 MST". For example:
import ( "fmt" "time" ) func main() { t := time.Now() fmt.Println(t.String()) // Output: 2023-05-09 11:33:42.134942534 -0500 CST }
If you require a custom format, you can use the Format() method by passing a layout string. For instance, to format a timestamp as "yyyy-MM-dd HH:mm:ss":
t := time.Now() fmt.Println(t.Format("2006-01-02 15:04:05")) // Output: 2023-05-09 11:33:42
In your code, you can rectify the error by converting the time.Time values to strings before adding them to the string array:
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.String(), US.Timestamp.String(), US.Created_date.String()} usersArray = append(usersArray, user) }
By using the String() method, you can successfully add the time.Time values as strings to your []string array.
The above is the detailed content of How to Convert Go's time.Time to String for String Array Appending?. For more information, please follow other related articles on the PHP Chinese website!