time.Time
から取得した値がありtime.Now()
、ちょうど 1 か月前の別の時刻を取得したいと考えています。
time.Sub()
減算は(別の が必要)で可能であることはわかっていますtime.Time
が、その結果は になり、time.Duration
逆のことが必要です。
ベストアンサー1
トーマス・ブラウンのコメントに応えて、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)
}
生産:
now: 2009-11-10 23:00:00 +0000 UTC
10 minutes ago: 2009-11-10 22:50:00 +0000 UTC
言うまでもなく、必要に応じて またはtime.Hour
のtime.Second
代わりにを使用することもできます。time.Minute