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
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.
Golang Zero Values For time. Time the zero value is 0001-01-01 00:00:00 +0000 UTC .
The specific date Go uses for date and time layouts in string formatting is 01/02 03:04:05PM '06 -0700 .
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.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With