我前段时间为我的项目编写了这段代码,它应该计算用户可能实现其饮食目标的目标日期。但在测试应用程序时,我发现无论进入目标日期的目标总是比创建日期大一个月。
这是代码
public String calcTD(SQLiteDatabase db){
String date = null;
myDataBase = db;
Cursor c = myDataBase.rawQuery("SELECT * FROM USER", null);
if (c!= null){
if (c.moveToFirst()){
String cdate = c.getString(c.getColumnIndex("CreatedDate"));
String type = c.getString(c.getColumnIndex("GoalType"));
if (type == "Maintain Weight")
date = cdate;
else{
int rate = c.getInt(c.getColumnIndex("Rate"));
float gw = c.getFloat(c.getColumnIndex("GoalWeight"));
float cw = getCW(db); //get current weight
float w = 0; int days = 0;
if (type == "Lose Weight")
w = cw - gw;
else if (type == "Gain Weight")
w = gw - cw;
switch (rate){
case 0: // the rate 250g/week
days = Math.round(w * 7 * 4);
break;
case 1: //the rate 500g/week
days = Math.round(w * 7 * 2);
break;
case 2://the rate 750g/week
days = Math.round(w * 7 * (4/3)) ;
break;
case 3:the rate 1kg/week
days = Math.round(w * 7);
break;
}
int y, m, d;
// the currentDate format (YYYYMMDD)
y = Integer.parseInt(cdate.substring(0,4));
m = Integer.parseInt(cdate.substring(4,6));
d = Integer.parseInt(cdate.substring(6,8));
GregorianCalendar i = new GregorianCalendar(y, m, d);
i.add(Calendar.DAY_OF_MONTH, days);
date = AllCmnMtd.getDate(i); // this will convert the date to a string with format (yyyymmdd)
}
}
}
return date;
}
很抱歉这是一个讨厌的人,但我的项目防守在两周之内,我在测试应用程序时遇到了很多错误! :(。
谢谢你,以及最好的问候
答案 0 :(得分:3)
Java的Calendar类使用基于0的索引数月。防爆。 0是1月,11是12月。
在放入Calendar对象之前从m中减去一个。