Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date
Let's go back into history for this tutorial's sake. Somehow you have invented a time traveling device powered by Golang and you are wanted to calculate the time when you suppose to end up in the past.
However, Golang has Time.Add()
function to calculate future dates and no Minus()
function to calculate past dates. So, how does one calculates past dates in Golang?
Solution:
Yes, the word Add
can be very limiting; however, do not let the Time.Add()
function name fools you. You still can calculate the past date by adding the present with a negative value. If Time.Add()
is to cumbersome. You can use Time.AddDate()
function as well.
For example:
package main
import (
"fmt"
"time"
)
func main() {
today := time.Now()
fmt.Println("Today is : ", today.Format("2006-01-02 03:04:00pm"))
// travel back 1 day
oneDay := time.Hour * -24 // minus 1 day
yesterday := today.Add(oneDay) // minus 1 day
fmt.Println("Yesterday is : ", yesterday.Format("2006-01-02 03:04:00pm"))
// for easier calculation, use AddDate() function instead
sevenDaysAgo := today.AddDate(0, 0, -7) // minus 7 days
fmt.Println("Seven days ago is : ", sevenDaysAgo.Format("2006-01-02 03:04:00pm"))
oneYearAgo := today.AddDate(-1, 0, 0) // minus one year
fmt.Println("One year ago is : ", oneYearAgo.Format("2006-01-02 03:04:00pm"))
}
Sample output:
Today is : 2016-06-14 01:08:00pm
Yesterday is : 2016-06-13 01:08:00pm
Seven days ago is : 2016-06-07 01:08:00pm
One year ago is : 2015-06-14 01:08:00pm
Hope this helps and happy coding!
References:
https://golang.org/pkg/time/#Time.Add
https://golang.org/pkg/time/#Time.AddDate
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
+29k Golang : JQuery AJAX post data to server and send data back to client example
+4.5k Linux/MacOSX : How to symlink a file?
+12.3k Golang : Arithmetic operation with numerical slices or arrays example
+4.1k Javascript : How to show different content with noscript?
+7k Golang : How to fix html/template : "somefile" is undefined error?
+17.3k Golang : delete and modify XML file content
+12.4k Golang : Add ASCII art to command line application launching process
+18.6k Golang : Delete duplicate items from a slice/array
+25.1k Golang : Daemonizing a simple web server process example
+5.4k Golang : Configure crontab to poll every two minutes 8am to 6pm Monday to Friday
+10.1k Fix ERROR 1045 (28000): Access denied for user 'root'@'ip-address' (using password: YES)
+35.1k Golang : Integer is between a range