Golang — Time utility functions you will always need

Implement custom functions that are not provided by time package
Jul 5 2022 · 5 min read

Introduction

Golang has a time package that serves time-related complexities most of the time.

Unlike other programming languages, it doesn’t contain all default utilities that can be used directly like Add day or Subtract a day, etc.
However, one can use its default methods and build their requirements.

In this blog, we will discuss some of the utilities like adding days or finding differences between timestamps, etc. Which we many times come around but are not available at the library level. May this article will save some of your minutes!

You won’t need more except the time package, Let’s dive in!



Add days to or subtract days from a given time

This function will add the number of days in the given timestamp. It can be also used to add years or months.

Of course, there is also a function Add() available for adding days to a given date. But it doesn’t add days, it adds hours. Basically, you can write like
t.Add(no. of days * 24).

However, it’s recommended to use AddDate() rather than Add(), as hour-based calculation won’t be accurate in case of daylight saving.

func AddDays(t time.Time, days int) time.Time {
   fmt.Println("currentTime: ", t)
   
   // AddDate(years int, months int, days int)
   newTime := t.AddDate(0, 0, days) 
   
   fmt.Println("newTime: ", newTime)
    
   return newTime
}


/* add 2 days to current time  */
AddDays(time.Now(), 2)

//output:
currentTime:  2022-07-01 22:28:09.732830978 +0530 IST m=+0.000055105
newTime:  2022-07-03 22:28:09.732827137 +0530 IST


/* subtract 2 days from current time */
AddDays(time.Now(), -2)

//output:
currentTime:  2022-07-01 22:28:09.733028278 +0530 IST m=+0.000251917
newTime:  2022-06-29 22:28:09.733025973 +0530 IST

As the time package doesn’t contain subtraction method for days, it allows subtraction using Add() only but with negative numbers.


Get Day-start time

To find the day start time from a given timestamp, we first need to find the day, month, and year of a given timestamp.

Then with zeroing out hours, minutes, and seconds, we can get starting of the day at a specified timezone.

func StartOfDay(t time.Time, timezone string) time.Time {
   location, _ := time.LoadLocation(timezone)
   year, month, day := t.In(location).Date()
   
   fmt.Println("currentTime: ", t)
   
   dayStartTime := time.Date(year, month, day, 0, 0, 0, 0, location)
   
   fmt.Println("StartOfDay: ", dayStartTime)
    
   return dayStartTime
}


/* get start of the day for given time */
StartOfDay(time.Now(), "Asia/Kolkata")

//output:
currentTime:  2022-07-01 22:47:16.791297534 +0530 IST m=+0.000346856
StartOfDay:  2022-07-01 00:00:00 +0530 IST

Get Day-end time

To get the end time, we just need to change hours, minutes, and seconds to 23, 59, and 59 respectively.

Also, we can get any time from 24 hours along with a specific timezone using this method.

func EndOfDay(t time.Time, timezone string) time.Time {
   location, _ := time.LoadLocation(timezone)
   year, month, day := t.In(location).Date()
   
   fmt.Println("currentTime: ", t)
   
   dayEndTime := time.Date(year, month, day, 23, 59, 59, 0, location)
   
   fmt.Println("EndOfDay: ", dayEndTime)
   
   return dayEndTime
}


/* get end of the day */
EndOfDay(time.Now(), "Asia/Kolkata")

//output:
currentTime:  2022-07-01 22:58:00.561086097 +0530 IST m=+0.000385053
EndOfDay:  2022-07-01 23:59:59 +0530 IST

Check whether the given two days are the same or not

To find out whether two given timestamps are same-day or not, we need to compare —
1. Day number of the year
2. Year

If they both are the same, the day is the same.

func IsSameDay(first time.Time, second time.Time) bool {
   return first.YearDay() == second.YearDay() && first.Year() == second.Year()
}


/* Check if given two days are same */

func main() {
   location, _ := time.LoadLocation("Asia/Kolkata")
   first := time.Date(2022, time.July, 01, 12, 30, 20, 0, location)
   second := time.Date(2022, time.July, 02, 0, 0, 50, 0, location)
   fmt.Println("first and second are same: ", IsSameDay(first, second))
}

//output:
first and second are same:  false

For example,
t.YearDay() will return 15 for date 15th January, 2022
t.Year() will give 2022 for the same.


Find a number of days between given timestamps

The time package provides the difference between two timestamps, in hours, minutes, and seconds(not in days).

The solution to finding the number of days between two timestamps is to get hours between them and divide it by 24. It will give a number of days between them.

func DiffInDays(start time.Time, end time.Time) int {
   return int(end.Sub(start).Hours() / 24)
}

/* difference between two timestamps */
func main() {
   location, _ := time.LoadLocation("Asia/Kolkata")
   start := time.Date(2022, time.July, 01, 12, 30, 20, 0, location)
   end := time.Date(2022, time.July, 31, 15, 0, 50, 0, location)
   fmt.Println("Days between start and end: ", DiffInDays(start, end))
}

//output:
Days between start and end:  30

To find the minute difference, run end.Sub(start).Minutes().


Find a number of weekdays(Mon, Tue,…) between two dates

To calculate specific weekdays(Mon, Tue, ...Sun) between a given range of time, the below function can be useful.

// day = Monday(1), Tuesday(2)...Sunday(7)
func FindNoOfDays(day int, start time.Time, end time.Time) int {
	totalDays := 0
	for start.Before(end) {
		if int(start.Weekday()) == day {
			totalDays += 1
		}
		start = AddDays(start, 1)
	}
	return totalDays
}


/* Find no. of mondays between two dates */
days := FindNoOfDays(1, time.Now(), time.Now().AddDate(0, 0, 26))
fmt.Println("No. of mondays between:", start, " and end:", end, "are: ", days)


// output:
No. of mondays between: 2022-07-01 12:30:20 +0530 IST  and end: 2022-07-31 15:00:50 +0530 IST are:  4

Where,
day = anything from 1 to 7, monday to sunday respectively.


Check if a given year is a leap year

Whenever we get into time computation things, often we need to calculate days and that can be varied with years(consider leap year), especially in the case of February.

However leap year is repeated after such an interval of 4 years, still, we will have to take it into account.

Below is the code that will help to determine whether a given year is a leap year or not.

func IsLeapYear(year int) bool {
   return year%4 == 0 && year%100 != 0 || year%400 == 0
}


/* check for leap year */

fmt.Println("2020 is leap year: ", IsLeapYear(2020))

//output:
2020 is leap year:  true

Here, we have checked 3 conditions,

  • year%4 == 0, i.e. year should be multiple of 4(as it’s repeated after 4 yrs),
  • year%100 != 0 || year%400 == 0, i.e. either year should be multiple of 400 or it should not be multiple of 100.

Try it with your favorite year!


Conclusion

That’s it for today. Hope these snippets will help you while working with the Golang time package. These are very basic functions though, you should always add your own that are commonly used in your projects.

As always, feedback and suggestions are welcome, please add them in the comment section below.

Similar Articles


nidhi-d image
Nidhi Davra
Web developer@canopas | Gravitated towards Web | Eager to assist


nidhi-d image
Nidhi Davra
Web developer@canopas | Gravitated towards Web | Eager to assist

canopas-logo
We build products that customers can't help but love!
Get in touch
background-image

Get started today

Let's build the next
big thing!

Let's improve your business's digital strategy and implement robust mobile apps to achieve your business objectives. Schedule Your Free Consultation Now.

Get Free Consultation
footer
Subscribe Here!
Follow us on
2024 Canopas Software LLP. All rights reserved.