r/learnjava • • Dec 22 '25

Getting the current date from number of milliseconds elapsed since epoch.

Hello everyone. I am having a hard time finding out the current date from the number of milliseconds elapsed since epoch. I wrote the following program that finds out the current year from the number of milliseconds elapsed since epoch:

public class Exercise06_24 {
	public static void main(String[] args) {
		long totalDays = getTotalNumberOfDays();
		System.out.println("Total number of days elapsed " + totalDays);
		System.out.println("The current year is " + getCurrentYear(totalDays));

	}

	public static long getTotalNumberOfDays() {
		final int MILLIS_PER_SECOND = 1000;
		final int HOURS_PER_DAY = 24;
		final int MINUTES_PER_HOUR = 60;
		final int SECONDS_PER_MINUTE = 60;

		long totalSeconds = System.currentTimeMillis() / MILLIS_PER_SECOND;

		long totalDays = totalSeconds / (HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE);

		return totalDays;
	}

	public static int getCurrentYear(long totalDays) {
		final int EPOCH_YEAR = 1970;

		int yearCounter = 0;

		for(int i = EPOCH_YEAR; (totalDays - (isLeapYear(i) ? 366 : 365)) >= 0; i++) {
			totalDays = totalDays - (isLeapYear(i) ? 366 : 365);
			yearCounter++; // count the number of years passed since EPOCH
		}

		return EPOCH_YEAR + yearCounter;
	}

	public static boolean isLeapYear(int year) {
		return ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));
	}
}

This program generates the following output:

Total number of days elapsed 20444
The current year is 2025

I know that there are libraries available for this kind of stuff but I am trying it out of curiosity and also as a solution to a programming exercise of Chapter-6 from Introduction to Java Programming and Data Structures by Y. Daniel Liang.

Now, with the current year obtained, how can I manually get the current month and the also the current day number ? Is there any kind of formula for this ? I am sorry if I sound dumb, but I would really like to know if there is any manual way of calculating the current date from the number of milliseconds elapsed since epoch ?

4 Upvotes

7 comments sorted by