Adding days to Epoch time [Java]

13.9k views Asked by At

Epoch time is the number of milliseconds that have passed since 1st January 1970, so if i want to add x days to that time, it seems natural to add milliseconds equivalent to x days to get the result

Date date = new Date();
System.out.println(date);
// Adding 30 days to current time
long longDate = date.getTime() + 30*24*60*60*1000;
System.out.println(new Date(longDate));

it gives the following output

Mon Dec 26 06:07:19 GMT 2016
Tue Dec 06 13:04:32 GMT 2016

I know i can use Calendar class to solve this issue, but just wanted to understand about this behaviour

4

There are 4 answers

0
Keval On BEST ANSWER

Its Because JVM is treating Value of multiplication 30*24*60*1000 as Int And multiplication result is out of range of Integer it will give result : -1702967296 intends of 2592000000 so its giving date smaller then current date

Try Below code :

public class Test {
public static void main(final String[] args) {
    Date date = new Date();
    System.out.println(date);
    // Adding 30 days to current time
    System.out.println(30 * 24 * 60 * 60 * 1000); // it will print -1702967296
    long longDate = (date.getTime() + TimeUnit.DAYS.toMillis(30));
    System.out.println(TimeUnit.DAYS.toMillis(30));
    date = new Date(longDate);
    System.out.println(date);
 }
}
0
Abhilekh Singh On

Try this:

 DateTime timePlusTwoDays = new DateTime().plusDays(days);
 long longDate = timePlusTwoDays.getTime();
 System.out.println(new Date(longDate));

Dateime class has:

 public DateTime plusDays(int days) {
        if (days == 0) {
            return this;
        }
        long instant = getChronology().days().add(getMillis(), days);
        return withMillis(instant);
 }
0
yshavit On

You're hitting integer overflow with your number. 30*24*60*60*1000 = 2,592,000,000, which is bigger than a signed, 32-bit integer can hold (2,147,483,647).

Use longs instead, by appending L onto any of the numbers: 1000L, for instance.

Note that if you want to deal with daylight savings time (to say nothing of leap seconds!), this still won't be enough. But if you're willing to assume that a day is always exactly 24 hours, using longs will fix your problem. (Time is a complicated thing, and I would suggest using a library like joda or Java 8's classes to handle it for you!)

0
SachinSarawgi On

Edit your code as follows:

long longDate = date.getTime() + 30*24*60*60*1000L;

It will work for sure.