java根据出生日期计算精确年龄

复制代码
import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.lang3.time.DurationFormatUtils;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 年龄工具类
 */
public class AgeUtils {

    /**
     * 计算详细年龄,精确到秒
     * @param birth
     * @return
     */
    public static String  getDetailedAge(String birth) throws Exception{
        String[] parsePatterns = {"yyyy-MM-dd HH:mm:ss"};
        Date date = DateUtils.parseDate(birth, parsePatterns);
        if(date.after(new Date())){
            return "err";
        }
        String s =  DurationFormatUtils.formatPeriod(date.getTime(), new Date().getTime(),   "yyyy-MM-dd HH:mm:ss");
        return s;
    }

    /**
     * 计算详细年龄,精确到秒
     * @param birth
     * @return
     */
    public static String  getDetailedAge(Date birth) throws Exception {
        String s =  DurationFormatUtils.formatPeriod(birth.getTime(), new Date().getTime(),   "yyyy-MM-dd HH:mm:ss");
        return s;
    }



    /**
     * 计算年龄,返回年龄和年龄单位的可精确到秒
     * @param birth
     * @return
     */
    public static Map<String,String> formatAge(Date birth) throws Exception{
        if(birth==null){
            return null;
        }
        String age=getDetailedAge(birth);
        String[] ages=age.split(" ");
        String[] ymd=ages[0].split("-");
        String[] hms=ages[1].split(":");
        Map<String, String> m=new LinkedHashMap<String, String>();
        m.put("y",ymd[0]);
        m.put("yu","年");
        m.put("m",ymd[1]);
        m.put("mu","月");
        m.put("d",ymd[2]);
        m.put("du","日");
        m.put("h",hms[0]);
        m.put("hu","时");
        m.put("n",hms[1]);
        m.put("nu","分");
        m.put("s",hms[2]);
        m.put("su","秒");
        return m;
    }

    public static Map<String,String> formatAge(String birth) throws Exception{
        String[] parsePatterns = {"yyyy-MM-dd HH:mm:ss"};
        Date date = DateUtils.parseDate(birth, parsePatterns);
        return formatAge(date);
    }

    public static void main(String[] args) throws Exception {
        System.out.println(formatAge("2020-07-15 15:00:00"));
    }
}
复制代码

 

 
posted @   cupful  阅读(1750)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示