58 lines
1.0 KiB
Go
58 lines
1.0 KiB
Go
package pasien
|
|
|
|
import "time"
|
|
|
|
type Age struct {
|
|
Years int
|
|
Months int
|
|
Days int
|
|
}
|
|
|
|
func CalculateAge(birthDate, now time.Time) Age {
|
|
// Pastikan jam = 00:00:00 biar konsisten
|
|
birthDate = time.Date(
|
|
birthDate.Year(), birthDate.Month(), birthDate.Day(),
|
|
0, 0, 0, 0, birthDate.Location(),
|
|
)
|
|
now = time.Date(
|
|
now.Year(), now.Month(), now.Day(),
|
|
0, 0, 0, 0, now.Location(),
|
|
)
|
|
|
|
years := now.Year() - birthDate.Year()
|
|
months := int(now.Month()) - int(birthDate.Month())
|
|
days := now.Day() - birthDate.Day()
|
|
|
|
// Kalau hari negatif, pinjam dari bulan
|
|
if days < 0 {
|
|
previousMonth := now.AddDate(0, -1, 0)
|
|
days += daysInMonth(previousMonth)
|
|
months--
|
|
}
|
|
|
|
// Kalau bulan negatif, pinjam dari tahun
|
|
if months < 0 {
|
|
months += 12
|
|
years--
|
|
}
|
|
|
|
if years < 0 {
|
|
return Age{}
|
|
}
|
|
|
|
return Age{
|
|
Years: years,
|
|
Months: months,
|
|
Days: days,
|
|
}
|
|
}
|
|
|
|
func daysInMonth(t time.Time) int {
|
|
firstOfNextMonth := time.Date(
|
|
t.Year(), t.Month()+1, 1,
|
|
0, 0, 0, 0, t.Location(),
|
|
)
|
|
lastOfMonth := firstOfNextMonth.AddDate(0, 0, -1)
|
|
return lastOfMonth.Day()
|
|
}
|