2015-10-14 256 views
26

我試圖將我的數據庫中的一些值添加到Go中的[]string。其中一些是時間戳。Golang:將time.Time轉換爲字符串

我得到的錯誤:

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

我可以轉換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) 
} 

編輯

我增加了以下內容。它現在有效,謝謝。

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

值得強調的事實,編譯器錯誤完全描述錯誤。您不能將類型Time放入字符串數組中。 –

+0

[如何使用yyyyMMddHHmmss格式格式化當前時間?](http://stackoverflow.com/questions/20234104/how-to-format-current-time-using-a-yyyymmddhhmmss-format) –

回答

46

可以使用Time.String()方法將time.Time轉換爲string。這使用格式字符串"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 

注:時間上的執行遊樂場總是被設置爲上方看到的值。在本地運行以查看當前的日期/時間。

還要注意的是使用Time.Format(),作爲佈局string你總是要經過的同時-called的參考時間在你想要的結果要格式化的方式格式化。這是記錄在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

弄清。爲了傳遞一個自定義的時間格式,你必須使用時間值'Mon Jan 2 15:04:05 -0700 MST 2006',並把這個時間放在你想要的任何格式。如果您使用此值傳遞,Go會理解格式。您不能使用任何其他時間值。這花了我一些時間來解決這個問題,並認爲將其添加爲評論 –

+0

@AhmedEssam謝謝,包括在答案。 – icza

+0

真棒拯救了我的一天,謝謝你。 – sector11

1

去遊樂場 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

當我嘗試fmt.Println(time.Now()。Format(「2017/20/01 13:53:35」))我越來越奇怪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

當我嘗試fmt。 println(time.Now()。Format(「2017/20/01 13:53:35」))我越來越奇怪21017/210/01 112:3012:1230 – irom

+1

使用fmt.Println(time.Now()。格式(「2006/01/02 15:04:05」)),因爲格式字符串是固定的,它是「2006 01 02 15 04 05」 – Hao

1

請找到簡單的解決方案convete日期&時間格式轉到郎。請找到下面的例子。

包裝鏈接:https://github.com/vigneshuvi/GoDateFormat

請找到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 
}