-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
66 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
package strings | ||
|
||
import ( | ||
"time" | ||
) | ||
|
||
type Birthday string | ||
|
||
// ToAge returns the age of the birthday | ||
// Example: | ||
// | ||
// input: "2020-01-01", today: 2023-10-01 result: [3, 9] | ||
func (b Birthday) ToAge(todayTime time.Time) ([2]int, error) { | ||
var ( | ||
layout = "2006-01-02" | ||
birthdayTime time.Time | ||
years int | ||
months int | ||
err error | ||
) | ||
|
||
if birthdayTime, err = time.Parse(layout, string(b)); err != nil { | ||
return [2]int{}, err | ||
} | ||
|
||
// Calculate the difference in years | ||
years = todayTime.Year() - birthdayTime.Year() | ||
|
||
// If today's month is less than birthday's month, subtract a year | ||
// Or if they are on the same month, but today's day is less than birthday's day, also subtract a year | ||
if todayTime.Month() < birthdayTime.Month() || | ||
(todayTime.Month() == birthdayTime.Month() && todayTime.Day() < birthdayTime.Day()) { | ||
years-- | ||
} | ||
|
||
// Calculate the difference in months | ||
if todayTime.Month() >= birthdayTime.Month() { | ||
months = int(todayTime.Month() - birthdayTime.Month()) | ||
} else { | ||
months = int(todayTime.Month() + 12 - birthdayTime.Month()) | ||
} | ||
|
||
// If today's day is less than birthday's day, subtract a month | ||
if todayTime.Day() < birthdayTime.Day() { | ||
months-- | ||
} | ||
|
||
return [2]int{years, months}, nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
package strings | ||
|
||
import ( | ||
"testing" | ||
"time" | ||
) | ||
|
||
func TestBirthday_ToAge(t *testing.T) { | ||
b := Birthday("1990-01-01") | ||
today := time.Date(2023, 10, 1, 0, 0, 0, 0, time.UTC) | ||
expected := [2]int{33, 9} | ||
if result, err := b.ToAge(today); err != nil { | ||
t.Errorf("ToAge(%v) returned an error: %v", b, err) | ||
} else if result != expected { | ||
t.Errorf("ToAge(%v) = %v, expected %v", b, result, expected) | ||
} | ||
} |