简体   繁体   English

从 Go 中的时间减去 time.Duration

[英]Subtracting time.Duration from time in Go

I have a time.Time value obtained from time.Now() and I want to get another time which is exactly 1 month ago.我有一个time.Time从获得的值time.Now()我想另一个时间,这正好是1个月前。

I know subtracting is possible with time.Sub() (which wants another time.Time ), but that will result in a time.Duration and I need it the other way around.我知道用time.Sub()减法是可能的(它需要另一个time.Time ),但这会导致time.Duration并且我需要time.Sub()

In response to Thomas Browne's comment, because lnmx's answer only works for subtracting a date, here is a modification of his code that works for subtracting time from a time.Time type.为了回应 Thomas Browne 的评论,因为lnmx 的答案仅适用于减去日期,这里是对他的代码的修改,用于从 time.Time 类型中减去时间。

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()

    fmt.Println("now:", now)

    count := 10
    then := now.Add(time.Duration(-count) * time.Minute)
    // if we had fix number of units to subtract, we can use following line instead fo above 2 lines. It does type convertion automatically.
    // then := now.Add(-10 * time.Minute)
    fmt.Println("10 minutes ago:", then)
}

Produces:产生:

now: 2009-11-10 23:00:00 +0000 UTC
10 minutes ago: 2009-11-10 22:50:00 +0000 UTC

Not to mention, you can also use time.Hour or time.Second instead of time.Minute as per your needs.更何况,你也可以使用time.Hourtime.Second代替time.Minute按您的需求。

Playground: https://play.golang.org/p/DzzH4SA3izp游乐场: https : //play.golang.org/p/DzzH4SA3izp

Try AddDate :尝试ADDDATE

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()

    fmt.Println("now:", now)

    then := now.AddDate(0, -1, 0)

    fmt.Println("then:", then)
}

Produces:产生:

now: 2009-11-10 23:00:00 +0000 UTC
then: 2009-10-10 23:00:00 +0000 UTC

Playground: http://play.golang.org/p/QChq02kisT游乐场: http : //play.golang.org/p/QChq02kisT

You can negate a time.Duration :您可以否定time.Duration

then := now.Add(- dur)

You can even compare a time.Duration against 0 :您甚至可以将time.Duration0进行比较:

if dur > 0 {
    dur = - dur
}

then := now.Add(dur)

You can see a working example at http://play.golang.org/p/ml7svlL4eW您可以在http://play.golang.org/p/ml7svlL4eW看到一个工作示例

There's time.ParseDuration which will happily accept negative durations, as per manual .根据手册time.ParseDuration乐意接受负持续时间。 Otherwise put, there's no need to negate a duration where you can get an exact duration in the first place.否则,没有必要否定一个持续时间,您可以首先获得确切的持续时间。

Eg when you need to substract an hour and a half, you can do that like so:例如,当您需要减去一个半小时时,您可以这样做:

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()

    fmt.Println("now:", now)

    duration, _ := time.ParseDuration("-1.5h")

    then := now.Add(duration)

    fmt.Println("then:", then)
}

https://play.golang.org/p/63p-T9uFcZo https://play.golang.org/p/63p-T9uFcZo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM