如何在Java中确定现在和任意未来日期之间的时间 [英] How to determine the time between now and an arbitrary future date in Java

查看:8
本文介绍了如何在Java中确定现在和任意未来日期之间的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试确定两个日期之间的时间量(其中一个是当前日期/时间,另一个是任意未来日期).我只使用原生 Java 和 Android API,但我在使用 GregorianCalendar 时遇到了一些问题.到目前为止,我的代码可以在下面看到,但我遇到的问题是两个日期之间的时间非常不准确.如您所见,我在本示例中已将未来日期设置为圣诞节,但它告诉我还有超过 62 天,这显然是错误的.

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;

在调试时我添加了 date.set(2011, 11, 23, 13, 1, 15);这更准确,但当我认为正确的天数是 31 时,它仍然显示 32 天.

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.

推荐答案

你代码中的问题是方法 calendar.set(2011, 12, 25, 0, 0, 0);你想要的是 calendar.set(2011, 11, 25, 0, 0, 0);

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);

你也可以使用Calendar.DECEMBER.

javadoc 对这个方法很清楚:

The javadoc is clear for this method:

  • @param month 用于设置MONTH日历的值场地.* 月份值是从 0 开始的.例如,0 表示一月.
  • @param month the value used to set the MONTH calendar field. * Month value is 0-based. e.g., 0 for January.

这篇关于如何在Java中确定现在和任意未来日期之间的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆