我正在做一个应用程序,该应用程序与根据给定的生日日期输入获取一个人的年龄有关。为此,我从下面的代码中获取从该日期到当前日期的总天数。
String strThatDay = "1991/05/10";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
Date d = null;
try {
try {
d = formatter.parse(strThatDay);
Log.i(TAG, "" +d);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
} catch (ParseException e) {
e.printStackTrace();
}
Calendar thatDay = Calendar.getInstance();
thatDay.setTime(d); //rest is the same....
Calendar today = Calendar.getInstance();
long diff = today.getTimeInMillis() - thatDay.getTimeInMillis();
long days = diff / (24 * 60 * 60 * 1000);
从这段代码中我得到了总天数。所以我的要求是将总天数准确地转换为年、月和日..请帮助....
您应该使用Duration http://docs.oracle.com/javase/1.5.0/docs/api/javax/xml/datatype/Duration.html class :
Duration duration = new Duration();
duration.add( today );
duration.substract( birthDate);
int years = duration.getYears();
int months = duration.getMonths();
int days = duration.getDays();
其他一些替代方案包括使用专用于时间管理的库:Joda time。看计算年龄(年、月、日、小时、分钟和秒) https://stackoverflow.com/questions/4710206/calculate-age-in-years-months-days-hours-minutes-and-seconds?rq=1
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)