34

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?

Ariel Vardi
  • 797
  • 1
  • 7
  • 18
  • Do you mean that you need to find the number of days since the epoch, _and_ the number of weeks since the epoch, _and_ the number of months since the epoch? _Or_, do you mean you need to show the time since the epoch, using the most efficient representation with months, weeks, and days? – erickson May 27 '11 at 22:05
  • The first one. For a given date (usually now()), I need to get the number of days since epoch, _and_ the number of weeks, _and_ the number of months. – Ariel Vardi May 27 '11 at 22:20

7 Answers7

37

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
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
softarn
  • 5,327
  • 3
  • 40
  • 54
  • 20
    If only looking for epoch days, you can use java.time API directly LocalDate.now().toEpochDay() – axle_h Aug 08 '16 at 12:02
  • 2
    I suggest always specifying the time zone by passing a `ZoneId` object to `LocalDate.now( zoneId )` rather than rely implicitly on the JVM’s current default zone. That default can be changed at runtime at any moment by any code in any thread of any app within the JVM. – Basil Bourque Feb 07 '17 at 04:01
36

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
bamana
  • 1,625
  • 12
  • 15
  • 3
    This directly helped me solve my problem. There was one issue I bumped into which I'll share for posterity. I noticed that the `secondsBetween` method returned a value that differed from Java by ~65350 seconds, my fix was: (1) `epoch = new MutableDateTime(0l, DateTimeZone.UTC)` and (2) remove `epoch.setDate(0)`. My local timezone is GMT+1 by the way and I'm working with already existing timestamps. – pauluss86 Feb 21 '14 at 18:39
  • I think that `epoch.setTime(0)` is also necessary to get the time correct. – Matthew Nov 04 '16 at 04:52
  • 4
    The [Joda-Time](http://www.joda.org/joda-time/) project, now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), advises migration to the [java.time](http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes. – Basil Bourque Feb 07 '17 at 03:58
  • @BasilBourque Thanks for the mention about Joda-time's maintenance mode. Its the best library for Java projects upto v1.7 – Gaurav Jul 02 '18 at 10:40
  • 1
    @gaurav Much of the *java.time* functionality is back-ported to Java 6 and Java 7 in the *ThreeTen-Backport* project. Further adapted to earlier Android in the *ThreeTenABP* project. Joda-Time, java.time, and ThreeTen-Backport are all led by the same man, Stephen Colebourne. – Basil Bourque Jul 02 '18 at 16:34
19

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()
mindex
  • 1,606
  • 13
  • 18
11
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));
Visruth
  • 3,430
  • 35
  • 48
ferronrsmith
  • 1,110
  • 5
  • 28
  • 47
1
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);
Binil Thomas
  • 13,699
  • 10
  • 57
  • 70
  • Why DAY_OF_MONTH and not DAY_OF_YEAR? Would it make a difference? Seems like this would work for days, weeks, and months too, right? – Ariel Vardi May 27 '11 at 22:15
0

I wouldn't expect there to be an elegant way of doing it since it is not a very common requirement. I can't help but wonder why you want to do it...

But anyway, the way I would do it is to subtract the epoch date from the Calendar and then get the fields you want:

Calendar timeSinceEpoch = Calendar.getInstance();
timeSinceEpoch.add(Calendar.YEAR, -1970);

int yearsSinceEpoch = timeSinceEpoch.get(Calendar.YEAR);
int monthsSinceEpoch = timeSinceEpoch.get(Calendar.MONTH) + 12 * yearsSinceEpoch;
Gyan aka Gary Buyn
  • 12,242
  • 2
  • 23
  • 26
-3

Date.getTime() - Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

You can use this and knowledge of how many milliseconds are in the intervals you care about to do the calculations.

unholysampler
  • 17,141
  • 7
  • 47
  • 64
  • 7
    Since the invention of DST you can't be exactly sure about the number of (milli)seconds in a day or week. And to make things more complicated leap seconds also exist. – Arjan May 27 '11 at 22:01
  • 6
    Going this route would make it very difficult to calculate the number of months, because of the leap years and other weird calendar exceptions. – Ariel Vardi May 27 '11 at 22:02