我写了以下代码,但我总是得到......
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);
任何人都可以看到这个逻辑有什么问题,找到直到圣诞节的日子,小时,分钟和秒钟?
答案 0 :(得分: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 :(得分:0)
这两行是错误的:
final long diffHours = diff % 60
final long diffDays = diff % 24;
此外,您没有在xmas
上设置小时/分钟/秒/毫秒,因此它从当前时间获取小时,分钟和秒。例如,如果您在凌晨4:30:20运行该程序,那么它将为您提供圣诞节前4:30:20 AM的时间。你可能想要圣诞节的00:00:00之前的时间。