Subtract two dates in Java
Possible Duplicate:
Calculating the Difference Between Two Java Date Instances
I know this might be a duplicate thread. But I am trying to figure out a way to compute the difference between two dates. From jquery the date string is in the format 'yyyy-mm-dd'
. I read this as a String and converted to java Date like this
Date d1 = new SimpleDateFormat("yyyy-M-dd").parse((String) request.getParameter(date1));
Date d2 = new SimpleDateFormat("yyyy-M-dd").parse((String) request.getParameter(date2));
I want to compute the difference in the number of days between these two dates.
Note: I cannot use third party API's as those need to reviewed.
long diff = Math.abs(d1.getTime() - d2.getTime());
long diffDays = diff / (24 * 60 * 60 * 1000);
Date d1 = new SimpleDateFormat("yyyy-M-dd").parse((String) request.
getParameter(date1));
Date d2 = new SimpleDateFormat("yyyy-M-dd").parse((String) request.
getParameter(date2));
long diff = d2.getTime() - d1.getTime();
System.out.println("Difference between " + d1 + " and "+ d2+" is "
+ (diff / (1000 * 60 * 60 * 24)) + " days.");
Assuming that you're constrained to using Date
, you can do the following:
Date diff = new Date(d2.getTime() - d1.getTime());
Here you're computing the differences in milliseconds since the "epoch", and creating a new Date object at an offset from the epoch. Like others have said: the answers in the duplicate question are probably better alternatives (if you aren't tied down to Date
).
下一篇: Java中减去两个日期