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

编程入门 行业动态 更新时间:2024-10-18 06:02:44
本文介绍了如何在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中确定现在和任意未来日期之间的时间

本文发布于:2023-11-22 14:45:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617862.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:日期   未来   时间   如何在   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!