我想为我的应用创建一个孕期计算器。我想抓住用户在日期时间选择器中选择的日期,并将该日期提前9个月和10天,然后在textView中打印出来。我可以从日期选择器中获取日期并将日期打印到textView中,但我现在需要做的是将日期提前9个月和10天。有任何想法吗?这是我当前的代码,用于从日期选择器中获取日期并将其打印到文本视图。
public class GestationPeriod extends Activity {
DatePicker date;
TextView gestationperiodView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gestationperiod);
setupVariables();
}
public void calculate(View v){
int gestationPeriodMonth = 9;
int gestationPeriodDay = 10;
int year = date.getYear();
int month = date.getMonth();
int day = date.getDayOfMonth();
gestationperiodView.setText("" + day + " / " + month + " / " + year);
}
private void setupVariables(){
date = (DatePicker) findViewById(R.id.datePicker1);
gestationperiodView = (TextView) findViewById(R.id.editText1);
}
非常感谢您的帮助。
答案 0 :(得分:1)
使用java.util.Calendar.add(int field, int amount)。获得日,月,年和gestationperiodView.setText
之后,插入:
Calendar c = new Calendar();
c.set(year, month-1, day);
c.add(Calendar.DAY_OF_MONTH, gestationPeriodDay);
c.add(Calendar.MONTH, gestationPeriodMonth);
day = c.get(Calendar.DAY_OF_MONTH);
month = c.get(Calendar.MONTH) + 1;
year = c.get(Calendar.YEAR);