Find Number of Days Between Two Given Dates in Java
Sometimes we need to find the number of days between two given dates. Earlier, I used Calendar and manually calculated the difference between the dates.
With Java 8 and later, this can be done much more easily using the java.time package.
import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; public class FindDays { public static void main(String[] args) { String str1 = "20/01/2013"; String str2 = "28/03/2013"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy"); LocalDate date1 = LocalDate.parse(str1, formatter); LocalDate date2 = LocalDate.parse(str2, formatter); long days = ChronoUnit.DAYS.between(date1, date2); System.out.println("Final Days.... " + days); } }Output:
Final Days.... 67
How it works
DateTimeFormatter is used to tell Java the format of the input dates.
LocalDate represents a date without a time or timezone.
ChronoUnit.DAYS.between() calculates the number of days between the two dates.
For example:
20/01/2013 → 28/03/2013 = 67 days
The older Calendar approach can still be found in existing Java applications, but for new development, the java.time API is generally the better choice.
No comments:
Post a Comment