mdpasien add edit
This commit is contained in:
42
utils/getage.utils.go
Normal file
42
utils/getage.utils.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
func daysInMonth(t time.Time) int {
|
||||
firstDayOfMonth := time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, t.Location())
|
||||
firstDayOfNextMonth := firstDayOfMonth.AddDate(0, 1, 0)
|
||||
return int(firstDayOfNextMonth.Sub(firstDayOfMonth).Hours() / 24)
|
||||
}
|
||||
func CalculateStringAge(birthDateStr string) (int, int, int, error) {
|
||||
layout := "2006-01-02"
|
||||
birthDate, err := time.Parse(layout, birthDateStr)
|
||||
if err != nil {
|
||||
return 0, 0, 0, err
|
||||
}
|
||||
|
||||
currentDate := time.Now()
|
||||
if currentDate.Before(birthDate) {
|
||||
return 0, 0, 0, fmt.Errorf("birth date is in the future")
|
||||
}
|
||||
|
||||
years := currentDate.Year() - birthDate.Year()
|
||||
months := int(currentDate.Month() - birthDate.Month())
|
||||
days := currentDate.Day() - birthDate.Day()
|
||||
|
||||
// Adjust if current month and day are before birth month and day
|
||||
if days < 0 {
|
||||
previousMonth := currentDate.AddDate(0, -1, 0)
|
||||
days += daysInMonth(previousMonth)
|
||||
months--
|
||||
}
|
||||
|
||||
if months < 0 {
|
||||
years--
|
||||
months += 12
|
||||
}
|
||||
|
||||
return years, months, days, nil
|
||||
}
|
||||
Reference in New Issue
Block a user