I write this code for my project some time ago, It should calculate the target date the user probably achieve his diet goal. but in testing the application I find out that whatever the goal entered the target date always be one month greater the date created.
this is the code
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;
}
Java's Calendar class uses 0 based indexes for months. Ex. 0 is January and 11 is December.
Subtract one from m before you put into the Calendar object.