我正在做一个与根据给定的生日日期输入来获取一个人的年龄有关的应用程序。为此,我从下面的代码获取从该日期到当前日期的总天数。
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
类:
Duration duration = new Duration();
duration.add( today );
duration.substract( birthDate);
int years = duration.getYears();
int months = duration.getMonths();
int days = duration.getDays();
其他一些选择包括使用专用于时间管理的库:Joda time。参见Calculate age in Years, Months, Days, Hours, Minutes, and Seconds
关于Android如何将总天数准确地更改为年,月和日?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12739428/