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")); } }
本文来自博客园,作者:cupful,转载请注明原文链接:https://www.cnblogs.com/cupful/p/16566927.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)