-3

I need to get difference between two dates using Java. I need my result to be in months and year of month.

Example:

Startdate = 2015-04-03 enddate = 2015-05-03 Result should be APR-MAY 2015

Startdate = 2015-12-03 enddate = 2015-01-03 Result should be DEC-2015,JAn-2016

i need to set that value into textview how can i set this plz help me .

Yury Fedorov
  • 14,508
  • 6
  • 50
  • 66
Kishan patel
  • 214
  • 1
  • 12

2 Answers2

1
    String startdate = "2015-11-30";
    String enddate = "2016-1-30";

    DateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
    DateFormat outputFormater = new SimpleDateFormat("MMM-yyyy");

    Calendar beginCalendar = Calendar.getInstance();
    Calendar finishCalendar = Calendar.getInstance();

    try {
          beginCalendar.setTime(formater.parse(startdate));
          finishCalendar.setTime(formater.parse(enddate));

          if (beginCalendar.get(Calendar.MONTH) != finishCalendar.get(Calendar.MONTH)){
              beginCalendar.set(Calendar.DAY_OF_MONTH, 1);
              finishCalendar.set(Calendar.DAY_OF_MONTH, 2);
          }

          do {
                // add one month to date per loop
                String month_year = outputFormater.format(beginCalendar.getTime());
                Log.d("Date_Range", month_year);
                beginCalendar.add(Calendar.MONTH, 1);
          } while (beginCalendar.before(finishCalendar));
    } catch (ParseException e) {
         e.printStackTrace();
    }

So by this you will get month and year between start date and end date in MMM-yyyy format. You can handle the result in the way you want by splitting month_year string @ "-" separator.

Rajen Raiyarela
  • 5,526
  • 4
  • 21
  • 41
0

You can use SimpleDateFormat.
EDIT: Try this

SimpleDateFormat formatter = new SimpleDateFormat("yyyy");

Check if your dates are in the same year by getting the year of the calendar.

int year1=Integer.pareInt(formatter.format(calendar1.getTime()));
int year2=Integer.pareInt(formatter.format(calendar2.getTime()));
year=year1-year2;

and then print result based on the year

formatter=new SimpleDateFormat("MMM");
if(year==0)
   System.out.println(formatter.format(calendar1)+"-"+formatter.format(calendar2)+" "+ year);
else
   System.out.println(formatter.format(calendar1)+"-"+year1+","+formatter.format(calendar2)+"-"+year2);
Drilon Blakqori
  • 2,796
  • 2
  • 17
  • 25