Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang set value on time.Time

Tags:

go

package main

import (
    "fmt"
    "reflect"
)

func main() {
    type t struct {
        N int
    }
    var n = t{42}
    fmt.Println(n.N)
    reflect.ValueOf(&n).Elem().FieldByName("N").SetInt(7)
    fmt.Println(n.N)
}

The prog below works the question is how do I do this with time.Time type like

package main

import (
    "fmt"
    "reflect"
    "time"
)

func main() {
    type t struct {
        N time.Time
    }
    var n = t{ time.Now() }
    fmt.Println(n.N)
    reflect.ValueOf(&n).Elem().FieldByName("N"). (what func)   (SetInt(7) is only for int)         // there is not SetTime
    fmt.Println(n.N)
}

This is important because I plan to use it on generic struct

I really appreciate your help on this

like image 208
user3715287 Avatar asked Jun 06 '14 14:06

user3715287


People also ask

How can I get time in go?

If you want a timestamp reflecting the number of seconds elapsed since January 1, 1970 00:00:00 UTC, use time. Now(). Unix() or time.

What is the zero value of time time in Golang?

Golang Zero Values For time. Time the zero value is 0001-01-01 00:00:00 +0000 UTC .

How do you represent time in Golang?

The specific date Go uses for date and time layouts in string formatting is 01/02 03:04:05PM '06 -0700 .

What does time duration do in Golang?

Duration has a base type int64. Duration represents the elapsed time between two instants as an int64 nanosecond count”. The maximum possible nanosecond representation is up to 290 years.


1 Answers

Simply call Set() with a reflect.Value of the time you want to set:

package main

import (
    "fmt"
    "reflect"
    "time"
)

func main() {
        type t struct {
                N time.Time
        }
        var n = t{time.Now()}
        fmt.Println(n.N)

        //create a timestamp in the future
        ft := time.Now().Add(time.Second*3600)

        //set with reflection
        reflect.ValueOf(&n).Elem().FieldByName("N").Set(reflect.ValueOf(ft))

        fmt.Println(n.N)
}
like image 164
Not_a_Golfer Avatar answered Oct 08 '22 18:10

Not_a_Golfer