嘿我需要制作一个倒计时天/小时/分钟/秒的程序,直到y2k38我得到了代码,但是我有一个逻辑错误,我得到错误的数字,持续几小时和几秒钟。继承我的代码:
public class Assignment1 {
public static void main(String[] args) {
long now = System.currentTimeMillis();
// The problem will occur at 2^31 seconds
long y2k38 = (long) Math.pow(2, 31)*1000;
// Assigning the time intervals values based on eachother
long diffsec = (y2k38-now)/1000;
long diffmin = diffsec/60;
long diffhours = diffmin/60;
long diffdays = diffhours/24;
// issuing a print statement to output the days,hours..etc until y2k38
System.out.printf(
"%d days\n"+
"%d hours\n"+
"%d minutes\n"+
"%d seconds\n",
(diffdays),(diffmin%60), (diffsec%3600),(diffsec%60));
}
}
答案 0 :(得分:0)
您的计算非常奇怪,您可以按如下方式修改和打印它们:
long diffsecs = (y2k38 - now) / 1000;
long diffmins = (diffsecs / 60) % 60;
long diffhours = (diffsecs / 60 / 60) % 24;
long diffdays = diffsecs / 60 / 60 / 24;
diffsecs = diffsecs % 60;
System.out.printf("%d days, %d hours, %d minutes, d seconds\n",
diffdays, diffhours, diffmins, diffsecs);
这给你类似的东西:
8126 days, 22 hours, 42 minutes, 21 seconds
大致符合您的需要。
答案 1 :(得分:0)
您将差异转换为总天数/小时/分钟/秒。相反,您希望从查找日期开始,并使用提醒查找小时数等等。
long diff = y2k38 - now;
long diffdays = diff/(24*60*60*1000);
diff = diff%(24*60*60*1000);
long diffhours = diff/(60*60*1000);
diff = diff%(60*60*1000);
long diffmin = diff/(60*1000);
diff = diff%(60*1000);
long diffsec = diff/1000;
通过
计算y2k38值也更快long y2k38 = ((long)(Integer.MAX_VALUE) + 1)*1000;