Write a java program to find the difference between Dates in months.

Given a method with two date strings in “yyyy-mm-dd” format as input. Write code to find the difference between two dates in months.

The return type of the output is an integer which returns the difference between two dates in months.

Input and Output Format:

Input consists of two date strings.

The format of date : yyyy-mm-dd.

The output is an integer.

Refer sample output for formatting specifications.

Sample Input 1:



Sample Output 1:


Sample Input 2:



Sample Output 2:


Find the difference between Dates in months in Java.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws ParseException, IOException {
             BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
             String s1 = br.readLine();
             String s2 = br.readLine();
public static int monthsBetweenDates(String s1, String s2) throws ParseException {
                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
                                Date d1=sdf.parse(s1);
                                Date d2=sdf.parse(s2);
                Calendar cal=Calendar.getInstance();
                                int months1=cal.get(Calendar.MONTH);
                                int year1=cal.get(Calendar.YEAR);
                                int months2=cal.get(Calendar.MONTH);
                                int year2=cal.get(Calendar.YEAR);
                int n=((year2-year1)*12)+(months2-months1);
                return n;

Add a Comment

Your email address will not be published. Required fields are marked *

10 + eight =