Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtracting time.Duration from time in Go

Tags:

datetime

go

I have a time.Time value obtained from time.Now() and I want to get another time which is exactly 1 month ago.

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.

like image 455
Martijn van Maasakkers Avatar asked Oct 06 '22 02:10

Martijn van Maasakkers


People also ask

How do I subtract hours from a timestamp?

To subtract hours from a given timestamp, we are going to use the datetime and timedelta classes of the datetime module. Step 1: If the given timestamp is in a string format, then we need to convert it to the datetime object. For that we can use the datetime. strptime() function.

How do I add time duration in Golang?

Add() function in Go language is used to add the stated time and duration. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions. Here, “t” is the stated time and “d” is the duration that is to be added to the time stated.


1 Answers

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.

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.

Playground: https://play.golang.org/p/DzzH4SA3izp

like image 131
cchio Avatar answered Oct 09 '22 07:10

cchio