Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding days to Epoch time [Java] [duplicate]

Tags:

java

epoch

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

like image 471
Paras Diwan Avatar asked Aug 12 '26 00:08

Paras Diwan


1 Answers

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);
 }
}
like image 180
Keval Avatar answered Aug 13 '26 13:08

Keval