```go
func GetYearDiffer(start_time, end_time string) int {
var Age int64
var pslTime string
if strings.Index(start_time, ".") != -1 {
pslTime = "2006.01.02"
} else if strings.Index(start_time, "-") != -1 {
pslTime = "2006-01-02"
} else {
pslTime = "2006/01/02"
}
t1, err := time.ParseInLocation(pslTime, start_time, time.Local)
t2, err := time.ParseInLocation("2006-01-02", end_time, time.Local)
if err == nil && t1.Before(t2) {
diff := t2.Unix() - t1.Unix()
Age = diff / (3600 * 365 * 24)
return int(Age)
} else {
return int(Age)
}
}
```
我也在写一个计算年龄的代码段,与君分享(PS:需求是不用精确到日)
```
if PbBirthday != "" {
birthday := strings.Split(order.PbBirthday,"-")
if len(birthday) < 3 {
return nil,errors.New("出生日期格式解析错误")
}
birYear,_ := strconv.Atoi(birthday[0])
birMonth,_ := strconv.Atoi(birthday[1])
age := time.Now().Year() - birYear
if int(time.Now().Month()) < birMonth {
age--
}
return age,nil
} else {
return nil,errors.New("出生日期为空")
}
```
#2
更多评论
1.一年又不是一定是365天
2.golang有time.duration类型,转成时间戳再减是什么骚操作……
3.出错了返回0又是什么骚操作……
最后,计算年龄这一块不是应该算年的差值,然后根据月份的大小进行调整就好了么……
#1