// This program determines what year it is right now and what day of the year // it is. For a non-leap year, the day-of-year will be between 1 and 365. // For a leap year, it will be between 1 and 366. public class Days2 { public static void main(String[] args) { long millis = System.currentTimeMillis(); // we subtract 1/3 to account for Pacific Time being 8 hours // behind Greenwich Mean Time; we add 1 because 1/1/70 should // be considered day 1 of 1970, not day 0 int days = (int) (toDays(millis) - 1.0 / 3.0 + 1); int year = 1970; // This loop subtracts 365 for non-leap years and subtracts // 366 for leap years until the number of days is in the // appropriate range (<= 365 for non-leap, <= 366 for leap). while ((days > 365 && year % 4 != 0) || (days > 366 && year % 4 == 0)) { if (year % 4 == 0) { days -= 366; year++; } else { days -= 365; year++; } } // the code above could be improved by factoring out the common line of // code "year++" in the if/else, but the code above is closer in // structure to the code that caused the infamous Zune bug on 12/31/08: /* while (days > 365) { if (year % 4 == 0) { if (days > 366) { days -= 366; year++; } } else { days -= 365; year++; } } */ System.out.println("millis = " + millis); System.out.println("year = " + year); System.out.println("days = " + days); } // converts milliseconds to days public static double toDays(double millis) { return millis / 1000.0 / 60.0 / 60.0 / 24.0; } }