Get the number of days, weeks, and months, since Epoch in Java

I'm trying to get the number of days, weeks, months since Epoch in Java.

The Java Calendar class offers things like calendar.get(GregorianCalendar.DAY_OF_YEAR), or Calendar.get(GregorianCalendar.WEEK_OF_YEAR), which is a good start but it doesn't do exactly what I need.

Is there an elegant way to do this in Java?


You can use the Joda Time library to do this pretty easily - I use it for anything time related other than using the standard Java Date and Calendar classes. Take a look at the example below using the library:

MutableDateTime epoch = new MutableDateTime();
epoch.setDate(0); //Set to Epoch time
DateTime now = new DateTime();

Days days = Days.daysBetween(epoch, now);
Weeks weeks = Weeks.weeksBetween(epoch, now);
Months months = Months.monthsBetween(epoch, now);

System.out.println("Days Since Epoch: " + days.getDays());
System.out.println("Weeks Since Epoch: " + weeks.getWeeks());
System.out.println("Months Since Epoch: " + months.getMonths());

When I run this I get the following output:

Days Since Epoch: 15122
Weeks Since Epoch: 2160
Months Since Epoch: 496

java.time

Use the java.time classes built into Java 8 and later.

LocalDate now = LocalDate.now();
LocalDate epoch = LocalDate.ofEpochDay(0);

System.out.println("Days: " + ChronoUnit.DAYS.between(epoch, now));
System.out.println("Weeks: " + ChronoUnit.WEEKS.between(epoch, now));
System.out.println("Months: " + ChronoUnit.MONTHS.between(epoch, now));

Output

Days: 16857
Weeks: 2408
Months: 553

I'm kind of surprised that almost all answers are actually calculating days between epoch and now. With java.time.LocalDate it's as simple as:

LocalDate.now().toEpochDay()

Long currentMilli = System.currentTimeMillis();
Long seconds = currentMilli / 1000;
Long minutes = seconds / 60;
Long hours = minutes / 60;
Long days = hours / 24;
System.out.println("Days since epoch : "  + days);

or

System.out.println("Days since epoch : "  + ((int) currentMilli / 86400000));

Calendar now = Calendar.getInstance();
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(0); // start at EPOCH

int days = 0
while (cal.getTimeInMillis() < now.getTimeInMillis()) {
  days += 1
  cal.add(Calendar.DAY_OF_MONTH, 1) // increment one day at a time
}
System.out.println("Days since EPOCH = " + days);