173

I'm trying to add some values from my database to a []string in Go. Some of these are timestamps.

I get the error:

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

Can I convert time.Time to 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

I added the following. It works now, thanks.

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")
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
A.D
  • 2,150
  • 3
  • 13
  • 19
  • It is worth highlighting the fact the compiler error describes the error completely. You cannot put a type Time in an array of a strings. – Ben Campbell Oct 14 '15 at 13:59
  • Possible duplicate of [How to format current time using a yyyyMMddHHmmss format?](http://stackoverflow.com/questions/20234104/how-to-format-current-time-using-a-yyyymmddhhmmss-format) – Oleksandr Savchenko May 11 '17 at 11:57
  • I couldn't get some of the suggestions working, I used `time.Now().String()` for now – Mark Robson Nov 02 '20 at 14:25

6 Answers6

263

You can use the Time.String() method to convert a time.Time to a string. This uses the format string "2006-01-02 15:04:05.999999999 -0700 MST".

If you need other custom format, you can use Time.Format(). For example to get the timestamp in the format of yyyy-MM-dd HH:mm:ss use the format string "2006-01-02 15:04:05".

Example:

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

Output (try it on the Go Playground):

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

Note: time on the Go Playground is always set to the value seen above. Run it locally to see current date/time.

Also note that using Time.Format(), as the layout string you always have to pass the same time –called the reference time– formatted in a way you want the result to be formatted. This is documented at 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.

Community
  • 1
  • 1
icza
  • 389,944
  • 63
  • 907
  • 827
  • 31
    Just to make clear. In order to pass a custom time format, you have to use the time value `Mon Jan 2 15:04:05 -0700 MST 2006` and put this time in whatever format you want. Go will understand the format if you passed it with this value. You cannot use any other time value. It took me sometime to figure this out and thought to add it as a comment – A.Essam Jan 04 '17 at 17:03
  • 1
    @AhmedEssam Thanks, included that in the answer. – icza Jan 05 '17 at 11:10
  • 1
    I wonder why `Mon Jan 2 15:04:05 -0700 MST 2006`, why not keep a simpler date or just `yyyy-mm.....`. – P.... Mar 28 '22 at 19:04
  • 2
    @P.... Because it contains the parts in numerical order: 1: Jan (1st month), 2: 2nd, 3: 15 (3pm), 4: 04, 5: 05, 6: 2006, 7: -7 (time zone). – icza Mar 28 '22 at 19:16
32
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
}    
Hao
  • 455
  • 4
  • 8
  • 1
    When I try fmt.Println(time.Now().Format("2017/20/01 13:53:35")) I am getting strange 21017/210/01 112:3012:1230 – irom Jan 21 '17 at 18:00
  • 3
    use fmt.Println(time.Now().Format("2006/01/02 15:04:05")) , because the format string is fixed, It's "2006 01 02 15 04 05" – Hao Feb 08 '17 at 08:04
10
package main

import (
    "fmt"
    "time"
)

func main() {
    v , _ := time.Now().UTC().MarshalText()
    fmt.Println(string(v))
}

Output : 2009-11-10T23:00:00Z

Go Playground

Sonu Sharma
  • 304
  • 4
  • 13
  • To future generations who read this and are too lazy to consult the docs for the details (like me): the MarshalText() method returns a byte array aka byte slice and an error. – MartinThurn Nov 04 '22 at 20:11
3

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)
}
Community
  • 1
  • 1
firebitsbr
  • 770
  • 6
  • 10
  • When I try fmt.Println(time.Now().Format("2017/20/01 13:53:35")) I am getting strange 21017/210/01 112:3012:1230 – irom Jan 21 '17 at 17:59
  • because you do 20 which is not meaningful for go so 2 is the date which was 21 probably at that time and the extra 0 is just appended @irom – nikoss Apr 24 '18 at 11:54
3

Please find the simple solution to convete Date & Time Format in Go Lang. Please find the example below.

Package Link: https://github.com/vigneshuvi/GoDateFormat.

Please find the 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
}
Vignesh Kumar
  • 598
  • 4
  • 11
3
strconv.Itoa(int(time.Now().Unix()))
feuyeux
  • 1,158
  • 1
  • 9
  • 26