Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract two dates in Java [duplicate]

Tags:

java

date

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.

like image 971
user525146 Avatar asked Oct 23 '12 19:10

user525146


People also ask

Can we subtract date in Java?

The minusDays() method of LocalDate class in Java is used to subtract the number of specified day from this LocalDate and return a copy of LocalDate. For example, 2019-01-01 minus one day would result in 2018-12-31. This instance is immutable and unaffected by this method call.

How do you add and subtract dates in Java?

DATE field can be used to add or subtract dates in Java. Positive value passed into add() method will add days into date while negative values will subtract days from date in Java. Similarly Calendar. MONTH can be used to add and subtract months from date in Java.

How do I compare two dates?

In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.


1 Answers

Edit 2018-05-28 I have changed the example to use Java 8's Time API:

LocalDate d1 = LocalDate.parse("2018-05-26", DateTimeFormatter.ISO_LOCAL_DATE); LocalDate d2 = LocalDate.parse("2018-05-28", DateTimeFormatter.ISO_LOCAL_DATE); Duration diff = Duration.between(d1.atStartOfDay(), d2.atStartOfDay()); long diffDays = diff.toDays(); 
like image 81
uldall Avatar answered Sep 23 '22 12:09

uldall