java将来的日期,如何确定Java之间的现在和任意未来日期之间的时间

I'm currently trying to determine the amount of time between two dates (one of which is the present date/time, the other an arbitrary future date). I'm using native Java and the Android API only, but I'm having a few problems with GregorianCalendar. My code so far can be seen below, but the problem I'm having is that the time between the two dates is massively inaccurate. As you'll be able to see I've set the future date as Christmas day in this example, but it's telling me there's over 62 days until then, which is clearly wrong.

date = new GregorianCalendar();

currentTime = date.getTimeInMillis();

calendar = new GregorianCalendar();

calendar.set(2011, 12, 25, 0, 0, 0);

long difference = calendar.getTimeInMillis()-currentTime;

long x = difference / 1000;

seconds = x % 60;

x /= 60;

minutes = x % 60;

x /= 60;

hours = x % 24;

x /= 24;

days = x;

While debugging I added date.set(2011, 11, 23, 13, 1, 15); which was much more accurate, but it still displayed 32 days when I believe the correct amount of days is 31.

Thanks very much in advance for any help, much appreciated.

解决方案

the problem in your code is the method calendar.set(2011, 12, 25, 0, 0, 0);

what you want is calendar.set(2011, 11, 25, 0, 0, 0);

you can use Calendar.DECEMBER too.

The javadoc is clear for this method:

@param month the value used to set the MONTH calendar

field. * Month value is 0-based. e.g., 0 for January.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值