我正在尝试确定从某个日期开始的年龄段。有谁知道在Android中做这件事的一种干净的方法吗?显然,我有Java api可用,但直接的java api相当弱,我希望Android能帮我解决这个问题。
编辑:在安卓中使用Joda time的多个建议让我有点担心Android Java - Joda Date is slow和相关的问题。此外,对于这种大小的东西,引入一个没有随平台一起提供的库可能有些过头了。
发布于 2011-10-27 02:47:12
我知道你要求一个干净的解决方案,但这里有两个不好的解决方案:
static void diffYears1()
{
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Calendar calendar1 = Calendar.getInstance(); // now
String toDate = dateFormat.format(calendar1.getTime());
Calendar calendar2 = Calendar.getInstance();
calendar2.add(Calendar.DAY_OF_YEAR, -7000); // some date in the past
String fromDate = dateFormat.format(calendar2.getTime());
// just simply add one year at a time to the earlier date until it becomes later then the other one
int years = 0;
while(true)
{
calendar2.add(Calendar.YEAR, 1);
if(calendar2.getTimeInMillis() < calendar1.getTimeInMillis())
years++;
else
break;
}
System.out.println(years + " years between " + fromDate + " and " + toDate);
}
static void diffYears2()
{
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Calendar calendar1 = Calendar.getInstance(); // now
String toDate = dateFormat.format(calendar1.getTime());
Calendar calendar2 = Calendar.getInstance();
calendar2.add(Calendar.DAY_OF_YEAR, -7000); // some date in the past
String fromDate = dateFormat.format(calendar2.getTime());
// first get the years difference from the dates themselves
int years = calendar1.get(Calendar.YEAR) - calendar2.get(Calendar.YEAR);
// now make the earlier date the same year as the later
calendar2.set(Calendar.YEAR, calendar1.get(Calendar.YEAR));
// and see if new date become later, if so then one year was not whole, so subtract 1
if(calendar2.getTimeInMillis() > calendar1.getTimeInMillis())
years--;
System.out.println(years + " years between " + fromDate + " and " + toDate);
}https://stackoverflow.com/questions/7906301
复制相似问题