我正在用Java编写一个程序,该程序试图将毫秒转换为年,月,日,小时,分钟和秒。
public class convertexercise {
public static void main(String[] args) {
System.out.println("Current Time in milliseconds = " + System.currentTimeMillis());
long[] converter = new long [6];
converter[0] = System.currentTimeMillis() / (1000 * 60 * 60 * 24 * 365); // years
converter[1] = System.currentTimeMillis() / (1000 * 60 * 60 * 24 * 30); // months
converter[2] = System.currentTimeMillis() / (1000 * 60 * 60 * 24); // days
converter[3] = System.currentTimeMillis() / (1000 * 60 * 60); // hours
converter[4] = System.currentTimeMillis() / (1000 * 60); // minutes
converter[5] = System.currentTimeMillis() / 1000; // seconds
System.out.print(converter[0] + " years, " + converter[1] + " months, " + converter[2] + " days, " + converter[3] + " hours, " + converter[4] + " minutes, " + converter[5] + " seconds.");
}
}
Run Code Online (Sandbox Code Playgroud)
我的程序能够转换System.currentTimeMillis()为正确的天数,小时数,分钟数和秒数。但是,当转换为月份和年份时,它将得到错误的值(1045年和-903个月显然是错误的值)。
转换成年数和月数时,我到底做错了什么?
您会得到整数范围溢出。该数字1000 * 60 * 60 * 24 * 365太大,无法容纳整数。
而是使用长数字进行计算:
converter[0] = System.currentTimeMillis() / (1000L * 60 * 60 * 24 * 365); // years
Run Code Online (Sandbox Code Playgroud)
等等。
将1000设为长常量,将对所有乘法强制执行长整数运算。
| 归档时间: |
|
| 查看次数: |
343 次 |
| 最近记录: |