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

浙公网安备 33010602011771号