Change in Calendar date by default

1.5k Views Asked by At

I am having a strange problem here in android project. I am trying to convert the date into other date and for that, I am calculating the days between two dates. So, here is how I have implemented.

Calendar baseEngDate = new GregorianCalendar();
Calendar currentEngDate= new GregorianCalendar();
baseEngDate.set(startingEngYearForSelection, startingEngMonthForSelection, startingEngDayForSelection);
currentEngDate.set(engYear, engMonth, engDay);
long totalEngDaysCount = daysBetween(baseEngDate, currentEngDate);

This is my baseEngDate Calendar. The set method has 3 parameters which have following parameters and their default values are:

int startingEngYearForSelection = 1944;
int startingEngMonthForSelection = 1;
int startingEngDayForSelection = 1;

But, when I try to check the value of them in this function,

 private long daysBetween(Calendar startDate, Calendar endDate) {

        SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
        String inputString1 = null;
        String inputString2 = null;

        Date date1 = startDate.getTime();
        Date date2 = endDate.getTime();

        inputString1 = myFormat.format(date1);
        inputString2 = myFormat.format(date2);
        Log.e("String", inputString1); 
.
.
.

    }

I get this value in log, which is not what I expected to be:

2018-11-14 13:55:29.982 15712-15712/com.utilnepal E/String: 01 02 1944

It should have returned me 01 01 1944 but it returns 01 02 1994. why?

1

There are 1 best solutions below

3
On

apply this and get your date in desired format:

In Java Calender January is 0 and others so on increment 1  

startingEngMonthForSelection will be 0 instead of 1;

 int startingEngYearForSelection = 1944;
 int startingEngMonthForSelection = 0;
 int startingEngDayForSelection = 1;

long diff = endDate.getTimeInMillis() - startDate.getTimeInMillis(); 

     SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
     Calendar calendar = Calendar.getInstance();
     calendar.setTimeInMillis(diff);
     String date=formatter.format(calendar.getTime());