Skip to content

Commit

Permalink
增加birthday类型
Browse files Browse the repository at this point in the history
  • Loading branch information
mztlive committed Sep 25, 2023
1 parent 47ffda9 commit ff22302
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
49 changes: 49 additions & 0 deletions strings/birthday.go
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
}
17 changes: 17 additions & 0 deletions strings/birthday_test.go
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)
}
}

0 comments on commit ff22302

Please sign in to comment.