Search code examples
javaepoch

Adding days to Epoch time [Java]


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


Solution

  • 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);
     }
    }