我正在为保护期开发一个功能。有一个TextView和按钮。当用户单击按钮时,日历将打开。用户从日历中选择日期,此日期将设置为该TextView。现在有另一个TextView,一个编辑文本和一个微调器。微调器有两个值:月份和年份。当用户输入一些数字值(如13)并从微调器中选择月份或年份时,应更新第二个文本视图。
我试图这样做,但如果在编辑文本中添加的月数超过12,我的概念就出错了。请帮帮我。
//Month selected
if (selecteditem.equalsIgnoreCase("Month")) {
String ed = edit_warrenty.getText().toString();
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
String dateInString = edit_date.getText().toString();
Date date = null;
try {
date = formatter.parse(dateInString);
System.out.println("===date===" + date);
String date1 = formatter.format(date);
System.out.println("===formateer.formatdate==" + date1);
} catch (ParseException e) {
e.printStackTrace();
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Calendar c = Calendar.getInstance();
c.setTime(date);
int month = c.get(Calendar.MONTH) + 1;
int day = c.get(Calendar.DAY_OF_MONTH);
int year = c.get(Calendar.YEAR);
c.set(month, (month + Integer.parseInt(ed)));
int newmonth = month + Integer.parseInt(ed);
if (newmonth <= 12) {
c.set(newmonth, year, day);
tvwarrentyday.setText(day + "-" + newmonth + "-" + year);
} else {
int in = newmonth - 12;
int inn = month + in;
c.set(month, (month + in));
tvwarrentyday.setText(day + "-" + inn + "-" + year + 1);
}
//Year selected
}else if (selecteditem.equalsIgnoreCase("Year")) {
String ed = edit_warrenty.getText().toString();
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
String dateInString = edit_date.getText().toString();
Date date = null;
try {
date = formatter.parse(dateInString);
System.out.println("===date===" + date);
String date1 = formatter.format(date);
System.out.println("===formateer.formatdate==" + date1);
} catch (ParseException e) {
e.printStackTrace();
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Calendar c = Calendar.getInstance();
c.setTime(date);
int month = c.get(Calendar.MONTH) + 1;
int day = c.get(Calendar.DAY_OF_MONTH);
int year = c.get(Calendar.YEAR);
c.set(year, (year + Integer.parseInt(ed)));
int newyear = year + Integer.parseInt(ed);
c.set(newyear, year, day);
tvwarrentyday.setText(day + "-" + month + "-" + newyear);
} else {
tvwarrentyday.setText("");
}
答案 0 :(得分:0)
如果您愿意使用用户提供的数据创建一个句点,您可以在选择月份时执行类似的操作:
int newmonth = Integer.parseInt(ed);
c.add(Calendar.MONTH, newmonth);
选择年份时就像那样:
int newyear = Integer.parseInt(ed);
c.add(Calendar.YEAR, newyear);
您不必检查该值是否优于12。