WoeIs :
I'm writing a program in Java which seeks to convert milliseconds to years, months, days, hours, minutes, and seconds.
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.");
}
}
My program is able to convert System.currentTimeMillis()
to the correct number of days, hours, minutes, and seconds. However when converting to months and years, it gets the wrong values (1045 years and -903 months which are obviously wrong values).
What exactly have I done wrong when converting to years and months?
Henry :
You get an integer range overflow. The number 1000 * 60 * 60 * 24 * 365
is too large to fit into an integer.
Instead do the calculations with long numbers:
converter[0] = System.currentTimeMillis() / (1000L * 60 * 60 * 24 * 365); // years
and so on.
Making the 1000 a long constant, forces long integer arithmetic for all the multiplications.