Golang : Get future or past hours, minutes or seconds
Problem:
You need to calculate future or past minutes, hours or seconds from the current time. Ability to calculate future or past hours, minutes and seconds can be useful in interpolating data in smaller scale than one day. How to do that in Golang?
Solution:
Similar to calculating future by days tutorial, but a few levels down from days. We will still use the Add()
function, but will convert the input parameters with time.Hour
, time.Minute
and time.Second
. Run the code example below to get a better grasp.
Here you go!
package main
import (
"fmt"
"time"
)
func GetHourMinuteSecond(hour, minute, second time.Duration) time.Time {
return time.Now().Add(time.Hour*hour + time.Minute*minute + time.Second*second)
}
func main() {
now := time.Now()
fmt.Println("Now is : ", now.Format(time.ANSIC))
// get three minutes into future
threeMinutes := time.Minute * time.Duration(3)
future := now.Add(threeMinutes)
fmt.Println("Three minutes from now will be : ", future.Format(time.ANSIC))
// get 5 hours into past
backFiveHours := time.Hour * time.Duration(-5)
past := now.Add(backFiveHours)
fmt.Println("Five hours ago from now will be : ", past.Format(time.ANSIC))
// from a function
getTime := GetHourMinuteSecond(0, 0, 50)
fmt.Println("50 seconds from now is : ", getTime.Format(time.ANSIC))
getTime2 := GetHourMinuteSecond(-5, -9, 0)
fmt.Println("5 hours and 9 minutes ago from now is : ", getTime2.Format(time.ANSIC))
}
Sample output:
Now is : Sat May 6 15:13:32 2017
Three minutes from now will be : Sat May 6 15:16:32 2017
Five hours ago from now will be : Sat May 6 10:13:32 2017
50 seconds from now is : Sat May 6 15:14:22 2017
5 hours and 9 minutes ago from now is : Sat May 6 10:04:32 2017
Happy time traveling!
References:
https://www.socketloop.com/tutorials/golang-calculate-future-date-with-time-add-function
See also : Golang : Calculate future date with time.Add() function
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+11.4k Golang : Surveillance with web camera and OpenCV
+18.2k Golang : How to get hour, minute, second from time?
+8.3k Android Studio : Import third-party library or package into Gradle Scripts
+9.7k Golang : Convert octal value to string to deal with leading zero problem
+8.8k Golang : Get curl -I or head data from URL example
+5.7k Golang : List all packages and search for certain package
+19.9k Golang : Check if os.Stdin input data is piped or from terminal
+27.2k Golang : dial tcp: too many colons in address
+22.1k Golang : Read directory content with filepath.Walk()
+13.1k Golang : Generate Code128 barcode
+13.1k Golang : Verify token from Google Authenticator App
+13.5k Golang : Tutorial on loading GOB and PEM files