1

I'm currently working on a project and I face a problem in a function that returns the startTime of a call. Here is my code:

func (bt *Hc34) getStartDate(endTime time.Time, duration int) time.Time {
     startTime := endTime
     startTime.Second = endTime.Second - duration

     return startTime
}

And I get this error:

beater/hc34.go:268: invalid operation: endTime.Second - duration (mismatched types func() int and int)
beater/hc34.go:268: cannot assign to startTime.Second
icza
  • 389,944
  • 63
  • 907
  • 827

1 Answers1

2

time.Time has no exported field Second, so startTime.Second is invalid.

There is a Time.Add() method which you may use to add a time.Duration value to a time.Time value. And to subtract a duration from it, simply multiply the value you add with -1.

func (bt *Hc34) getStartDate(endTime time.Time, duration int) time.Time {
    return endTime.Add(time.Duration(-duration) * time.Second)
}

Example with a getStartDate() function (not method):

now := time.Now()
fmt.Println(now)
fmt.Println(getStartDate(now, 60))

Output on the Go Playground:

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

I also recommend to read this answer about using time.Duration values constructed from integers: Conversion of time.Duration type microseconds value to milliseconds

icza
  • 389,944
  • 63
  • 907
  • 827