默认情况下更改日历日期

时间:2018-11-14 08:18:41

标签: java android date-difference android-date java.util.calendar

我在android项目中遇到一个奇怪的问题。我试图将日期转换为其他日期,为此,我正在计算两个日期之间的天数。 所以,这就是我的实现方式。

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

这是我的baseEngDate日历。 set方法具有3个参数,这些参数具有以下参数,其默认值为:

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

但是,当我尝试在此函数中检查它们的值时,

 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); 
.
.
.

    }

我在日志中得到了这个值,而不是我期望的值:

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

应该返回我01 01 1944,但是返回01 021994。为什么?

1 个答案:

答案 0 :(得分:0)

应用此项并以所需格式获取日期:

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

startingEngMonthForSelection将为0而不是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());