2015-10-14 14 views
26

Sto cercando di aggiungere alcuni valori dal mio database a un []string in Go. Alcuni di questi sono timestamp.Golang: conversione time.Time a stringa

ottengo l'errore:

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

Posso convertire 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} 
    // ------------- 
    //^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

ho aggiunto il seguente. Funziona ora, grazie.

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

Vale la pena sottolineare il fatto l'errore del compilatore descrive completamente l'errore. Non puoi inserire un tipo Time in un array di stringhe. –

+0

Possibile duplicato di [Come formattare l'ora corrente usando il formato aaaaMMggHHmmss?] (Http://stackoverflow.com/questions/20234104/how-to-format-current-time-using-a-yyyymmsdhhmmss-format) –

risposta

46

È possibile utilizzare il metodo Time.String() per convertire un time.Time ad un string. Questo utilizza la stringa di formato "2006-01-02 15:04:05.999999999 -0700 MST".

Se è necessario un altro formato personalizzato, è possibile utilizzare Time.Format(). Ad esempio, per ottenere il timestamp nel formato yyyy-MM-dd HH:mm:ss utilizzare la stringa di formato "2006-01-02 15:04:05".

Esempio:

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

uscita (provate sul Go Playground):

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

Nota: il tempo on the Go parco giochi è sempre impostato al valore visto sopra. Eseguirlo localmente per vedere la data/ora corrente.

Si noti inoltre che l'utilizzo di Time.Format(), come il layout string devi sempre passare lo stesso tempo -definito il di riferimento tempo-formattato in un modo in cui si desidera che il risultato da formattare. Questo è documentato in 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.

+6

Just to to chiarire.Per passare un formato orario personalizzato, è necessario utilizzare il valore temporale "Mon Jan 2 15:04:05 -0700 MST 2006" e inserire questa volta nel formato desiderato. Go capirà il formato se lo hai passato con questo valore. Non è possibile utilizzare nessun altro valore temporale. Mi ci è voluto qualche tempo per capirlo e ho pensato di aggiungerlo come commento –

+0

@AhmedEssam Grazie, incluso quello nella risposta. – icza

+0

Impressionante mi ha salvato la giornata. – sector11

1

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) 
} 
+0

Quando provo fmt.Println (time.Now(). Format ("2017/20/01 13:53:35")) Sto diventando strano 21017/210/01 112: 3012: 1230 – irom

7
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 
}  
+0

Quando provo fmt. Println (time.Now(). Format ("2017/20/01 13:53:35")) Sto diventando strano 21017/210/01 112: 3012: 1230 – irom

+1

usa fmt.Println (time.Now(). Formato ("2006/01/02 15:04:05")), perché la stringa di formato è fissa, è "2006 01 02 15 04 05" – Hao

1

Si prega di trovare la soluzione più semplice per convete Data & Time Format in Go Lang. Si prega di trovare l'esempio qui sotto.

Link del pacchetto: https://github.com/vigneshuvi/GoDateFormat.

Trova le 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 
}