【发布时间】: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 [日历类] (tutorialspoint.com/java/util/java_util_calendar.htm) 来实现这一目标?
-
你为什么不使用 LocalDate Api ?
标签: java