在函数中对秒进行操作

huangapple go评论75阅读模式
英文:

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

huangapple
  • 本文由 发表于 2017年8月1日 16:39:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/45432924.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定