将年份添加到Java日历不起作用 [英] Add year to Java Calendar doesn't work
本文介绍了将年份添加到Java日历不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请在这方面告诉我:
我只是想在当前日期加10年,然后减去到期日期,以返回年数:
public int getMaxYears(){
int max = 0;
Calendar ten_year_later = Calendar.getInstance();
ten_year_later.setTime(new Date());
ten_year_later.add(Calendar.YEAR,10);
日历expiration = Calendar.getInstance();
expiration.setTime(expiration_date);
max =(int)(ten_year_later.getTimeInMillis() - expiration.getTimeInMillis())/(365 * 24 * 60 * 60 * 1000);
return max;
}
当我调试这个,日历总是保持在当前年。 p>
任何人?
解决方案
int / long转换有问题: 365 * 24 * 60 * 60 * 1000
其计算结果为31536000000,因此超过 Integer.MAX_VALUE
2147483647
此工作原理:
public static void main(String [] args){
Calendar ten_year_later = Calendar.getInstance();
System.out.println(ten_year_later.getTime());
ten_year_later.setTime(new Date());
ten_year_later.add(Calendar.YEAR,10);
System.out.println(ten_year_later.getTime());
日历expiration = Calendar.getInstance();
expiration.setTime(expiration.getTime());
long max =(ten_year_later.getTimeInMillis() - expiration.getTimeInMillis())/(365 * 24 * 60 * 60 * 1000L);
System.out.println(max+ max);
}
Please enlight me on this :
I'm simply trying to add 10 years to the current date then substract an expiration date from it to return the number of years:
public int getMaxYears() {
int max = 0;
Calendar ten_year_later = Calendar.getInstance();
ten_year_later.setTime(new Date());
ten_year_later.add(Calendar.YEAR, 10);
Calendar expiration = Calendar.getInstance();
expiration.setTime(expiration_date);
max = (int) (ten_year_later.getTimeInMillis() - expiration.getTimeInMillis())/(365 * 24 * 60 * 60 * 1000);
return max;
}
When I debug this, the calendar always stay at the current year.
Anyone ?
解决方案
You have a problem with int / long conversion: 365 * 24 * 60 * 60 * 1000
Which evaluates to 31536000000 and therefore exceeds Integer.MAX_VALUE
2147483647
This works:
public static void main(String[] args) {
Calendar ten_year_later = Calendar.getInstance();
System.out.println( ten_year_later.getTime() );
ten_year_later.setTime(new Date());
ten_year_later.add(Calendar.YEAR, 10);
System.out.println( ten_year_later.getTime() );
Calendar expiration = Calendar.getInstance();
expiration.setTime(expiration.getTime());
long max = (ten_year_later.getTimeInMillis() - expiration.getTimeInMillis())/(365 * 24 * 60 * 60 * 1000L);
System.out.println( "max " + max );
}
这篇关于将年份添加到Java日历不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文