【问题标题】:Converting milliseconds to months and years is not working properly将毫秒转换为月和年无法正常工作
【发布时间】:2018-09-30 12:44:45
【问题描述】:

我正在用 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.");
    }
}

我的程序能够将System.currentTimeMillis() 转换为正确的天数、小时数、分钟数和秒数。但是,当转换为月份和年份时,它会得到错误的值(1045 年和 -903 个月,这显然是错误的值)。

在转换为年和月时我到底做错了什么?

【问题讨论】:

标签: java


【解决方案1】:

你得到一个整数范围溢出。数字 1000 * 60 * 60 * 24 * 365 太大,无法放入整数。

改为使用长数字进行计算:

converter[0] = System.currentTimeMillis() / (1000L * 60 * 60 * 24 * 365); // years

等等。

将 1000 设为 long 常量,强制对所有乘法进行长整数运算。

【讨论】:

    猜你喜欢
    • 2012-01-02
    • 1970-01-01
    • 2021-06-09
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    • 2013-07-11
    • 2016-11-16
    • 1970-01-01
    相关资源
    最近更新 更多