![]() |
VOOZH | about |
Given two dates start_date and end_date with time in the form of strings, the task is to find the difference between two dates in Java. Examples:
Input: start_date = "10-01-2018 01:10:20", end_date = "10-06-2020 06:30:50" Output: 2 years, 152 days, 5 hours, 20 minutes, 30 seconds Input: start_date = "10-01-2019 01:00:00", end_date = "10-06-2020 06:00:00" Output: 1 years, 152 days, 5 hours, 0 minutes, 0 seconds
Method 1: Use SimpleDateFormat and Date class to find the difference between two dates. Below are the steps:
Below is the implementation of the above approach:
Difference between two dates is: 2 years, 152 days, 5 hours, 20 minutes, 30 seconds
Method 2: We can find the difference between two dates in a better way by using Java built-in class TimeUnit. Below is the implementation of the above approach:
Difference between two dates is: 2 years, 152 days, 5 hours, 20 minutes, 30 seconds
Method 3: Use Period class in Java to find the difference between two days. The Period.between() method is used to calculate the difference between two dates in years, months, and days. Below is the implementation of the above approach:
Difference between two dates is: 2 years, 5 months and 0 days