“datediff” and “person” Go packages

2 min readApr 5, 2022

Today I would like to announce two Go packages I recently created.

Like many other packages, I created these because I repeatedly copied the same code. I wanted to create a reusable component. All started from a person package and its minimal functionality to build a full name from multiple parts. Then I got the idea to extend the package with age-related functions, such as age in whole years and verifying whether a person is an adult. Initially, datediff was a part of the “person” package supporting age calculation. But later, I separated the packages.

datediff

It is a package to calculate and represent dates difference. Standard Go package time provides functionality to get the difference between two dates — Sub with the result is a time.Duration. The duration is practical when working with hours, minutes, seconds, etc. But it’s challenging when it’s required to represent dates difference in days, weeks, and months. Months or leap years don’t have a fixed amount of hours, making it hard to use hours as a base time unit. datediff package provides constructors and formaters that represent dates difference in full days, weeks, months and years. The package uses a “human-based” way to calculate dates difference—the same way as when we look at a calendar and count amount of weeks and days until vacation.

package mainimport(
"fmt"
"time"
"github.com/antklim/datediff"
)
func main() {
today, _ := time.Parse("2006-01-02", "2022-04-05")
vacation, _ := time.Parse("2006-01-02", "2022-04-28")
vacationIn, _ := datediff.NewDiff(today, vacation, "%W %D")
fmt.Printf("Until vacation %s", vacationIn)
// Output:
// Until vacation 3 weeks 2 days
}

person

This package provides methods to work with a person’s name and age. Initial full name builder functionality extended with the age calculator and validator whether a person is an adult.

package main

import (
"fmt"
"time"

"github.com/antklim/person"
)

func main() {
nameParts := []string{"John", " ", " Smith ", "Doe"}
fullName := person.FullName(nameParts)
fmt.Printf("Full name: %s\n", fullName)

dob := time.Now().AddDate(-20, 0, 0)
age, _ := person.Age(dob, "%Y")
fmt.Printf("Age: %s old\n", age)

adultAge := 18
isAdult, _ := person.IsAdult(dob, adultAge)
fmt.Printf("Is adult: %t\n", isAdult)
// Output:
// Full name: John Smith Doe
// Age: 20 years old
// Is adult: true
}

Thanks for reading, and I hope you will find these packages helpful. Please feel free to open an issue of PR if you would like to improve them.

References

--

--

Anton Klimenko
Anton Klimenko

Written by Anton Klimenko

Software Engineer and chef @CloudRecipesIO | https://antklim.com

No responses yet