Java中日期的毫秒差异

4
我写了以下代码,但总是得到... 4838399999 秒为: 59 分钟为: 59 小时为: 23 天为: 7
Calendar xmas = Calendar.getInstance();
final Calendar now = Calendar.getInstance();

xmas.set(Calendar.YEAR, 2011);
xmas.set(Calendar.MONTH, Calendar.DECEMBER);
xmas.set(Calendar.DAY_OF_MONTH, 25);

long milliseconds1 = now.getTimeInMillis();
long milliseconds2 = xmas.getTimeInMillis();
long diff = milliseconds2 - milliseconds1;
System.out.println(diff);
diff = diff / 1000;

final long diffSeconds = diff % 60;
System.out.println("Seconds is : " + diffSeconds);
diff = diff / 60;

final long diffMinutes = diff % 60;
System.out.println("Minutes is : " + diffMinutes);
diff = diff / 60;

final long diffHours = diff % 60;
System.out.println("Hours is : " + diffHours);
diff = diff / 24;

final long diffDays = diff % 24;
System.out.println("Days is : " + diffDays);

有人能看出在这个找到圣诞节的天数、小时数、分钟数和秒数的逻辑中有什么问题吗?

2个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
7
当你执行以下操作时:
diff = diff / 1000;
你正在永久失去余下的内容。应该是这样的:
long seconds = diff / 1000; // seconds is milliseconds / 1000
long milliseconds = diff % 1000; // remainder is milliseconds that are not composing seconds.
long minutes = seconds / 60;
seconds = seconds % 60;
long hours = minutes / 60;
minutes = minutes % 60;
同样的模式持续了过去的四个。

1
嗯,他不再需要余数了,所以这真的不是问题。 - ruakh
@ruakh,你是对的。我读得太快了,以为milliseconds在某个地方被使用了。 - Matthew Flaschen

0
这两行是错误的:
final long diffHours = diff % 60

final long diffDays = diff % 24;
另外,您没有在 xmas 上设置小时/分钟/秒/毫秒,因此它会从当前时间获取小时、分钟和秒。例如,如果您在上午4:30:20运行程序,则会告诉您距离圣诞节上午4:30:20还有多长时间。您可能希望知道距离圣诞节 00:00:00 还有多少时间。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,