我正在用 Java 編寫一個程序,試圖將毫秒轉(zhuǎn)換為年、月、日、小時、分鐘和秒。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."); }}我的程序能夠轉(zhuǎn)換System.currentTimeMillis()為正確的天數(shù)、小時數(shù)、分鐘數(shù)和秒數(shù)。但是,當(dāng)轉(zhuǎn)換為月份和年份時,它會得到錯誤的值(1045 年和 -903 個月顯然是錯誤的值)。轉(zhuǎn)換為年和月時我到底做錯了什么?
1 回答

一只甜甜圈
TA貢獻1836條經(jīng)驗 獲得超5個贊
你得到一個整數(shù)范圍溢出。該數(shù)字1000 * 60 * 60 * 24 * 365
太大而無法放入整數(shù)。
而是使用長數(shù)字進行計算:
converter[0] = System.currentTimeMillis() / (1000L * 60 * 60 * 24 * 365); // years
等等。
使 1000 成為一個長常數(shù),強制所有乘法的長整數(shù)算術(shù)。
添加回答
舉報
0/150
提交
取消