英文:
Operation on seconds in function
问题
我目前正在处理一个项目,遇到了一个返回通话的startTime
的函数的问题。以下是我的代码:
func (bt *Hc34) getStartDate(endTime time.Time, duration int) time.Time {
startTime := endTime
startTime.Second = endTime.Second - duration
return startTime
}
我得到了以下错误:
beater/hc34.go:268: invalid operation: endTime.Second - duration (mismatched types func() int and int)
beater/hc34.go:268: cannot assign to startTime.Second
请问有什么问题?
英文:
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
答案1
得分: 2
time.Time
没有导出字段Second
,所以startTime.Second
是无效的。
有一个Time.Add()
方法,您可以使用它将time.Duration
值添加到time.Time
值中。要从中减去持续时间,只需将您添加的值乘以-1
即可。
func getStartDate(endTime time.Time, duration int) time.Time {
return endTime.Add(time.Duration(-duration) * time.Second)
}
使用getStartDate()
函数(而不是方法)的示例:
now := time.Now()
fmt.Println(now)
fmt.Println(getStartDate(now, 60))
在Go Playground上的输出:
2009-11-10 23:00:00 +0000 UTC
2009-11-10 22:59:00 +0000 UTC
我还建议阅读关于使用从整数构造的time.Duration
值的这个答案:https://stackoverflow.com/questions/41503758/conversion-of-time-duration-type-microseconds-value-to-milliseconds-in-golang/41503910#41503910
英文:
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: https://stackoverflow.com/questions/41503758/conversion-of-time-duration-type-microseconds-value-to-milliseconds-in-golang/41503910#41503910
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论