I am trying to write a code to determine when the number of milliseconds since the beginning of 1970 will exceed the capacity of a long. The following code appears to do the job:
public class Y2K {
public static void main(String[] args) {
int year = 1970;
long cumSeconds = 0;
while (cumSeconds < Long.MAX_VALUE) {
// 31557600000 is the number of milliseconds in a year
cumSeconds += 3.15576E+10;
year++;
}
System.out.println(year);
}
}
This code executes within seconds and prints 292272992. If instead of using scientific notation I write cumSeconds as 31558000000L
, the program seems to take “forever” to run (I just hit pause after 10 mins or so). Also notice that writing cumSeconds in scientific notation does not require specifying that the number is a long
with L or l at the end.
System.out.println( 1970 + (long)Math.ceil( Long.MAX_VALUE/31557600000L ) );
– Suzetta