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

编程入门 行业动态 更新时间:2024-10-17 17:23:42
本文介绍了如何确定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 calendar 字段。 *月值为0。例如,1表示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:44:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617856.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:日期   未来   时间   Java

发布评论

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

>www.elefans.com

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