下面做的是:28天<= 日期 <=65周岁
//计算28天前的日期
public static final long _MAX_TIME = 28 * 24 * 60 * 60 * 1000L;
int inComingYear;
int inComingMonth;
int inComingDay;
Calendar calendarIn = Calendar.getInstance();
//设置系统时间是防止初始化日期控件时“日”显示为空
calendarIn.setTime(new Date(System.currentTimeMillis() - _MAX_TIME));
//传入的日期一定要在监听外设置,否者再次点击不能显示上次所选日期,而显示当前日期
inComingYear = calendarIn.get(Calendar.YEAR);inComingMonth = calendarIn.get(Calendar.MONTH);
inComingDay = calendarIn.get(Calendar.DAY_OF_MONTH);
insuredAge.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
long curTime = System.currentTimeMillis();
long maxTime = curTime - _MAX_TIME;
// 當前日期的65年前的日期
Calendar calendar2 = Calendar.getInstance();
// 得到一个Calendar的实例
calendar2.setTime(new Date());
// 设置时间为当前时间
calendar2.add(Calendar.YEAR, -65);
// 年份减1
Date minTimeCurrent = calendar2.getTime(); // 结果
DatePickerDialog datePickerDialog = new DatePickerDialog(
LifeHappyWinnerProductTrialActivity.this, Datelistener,
inComingYear, inComingMonth, inComingDay);
DatePicker datePicker = datePickerDialog.getDatePicker();
//一定要先设置最小值,再设置最大值,否则程序会崩
datePicker.setMinDate(minTimeCurrent.getTime());datePicker.setMaxDate(maxTime);
datePickerDialog.show();
}
});
private DatePickerDialog.OnDateSetListener Datelistener = new DatePickerDialog.OnDateSetListener() {
/**
* params:view:该事件关联的组件 params:myyear:当前选择的年 params:monthOfYear:当前选择的月
* params:dayOfMonth:当前选择的日
*/
@Override
public void onDateSet(DatePicker view, int myyear, int monthOfYear,
int dayOfMonth) {
// 修改year、month、day的变量值,以便以后单击按钮时,DatePickerDialog上显示上一次修改后的值
inComingYear = myyear;
inComingMonth = monthOfYear;
inComingDay = dayOfMonth;
// 更新日期
String month;
String dayof;
if ((monthOfYear + 1) < 10) {
month = "0" + (monthOfYear + 1);
} else {
month = (monthOfYear + 1) + "";
}
if (dayOfMonth < 10) {
dayof = "0" + dayOfMonth;
} else {
dayof = dayOfMonth + "";
}
ageDay = myyear + "-" + month + "-" + dayof;
SimpleDateFormat format = new SimpleDateFormat("yyyy");
int NowYear = Integer.parseInt(format.format(new Date()));
SimpleDateFormat formatM = new SimpleDateFormat("MM");
int monthNow = Integer.parseInt(formatM.format(new Date()));
SimpleDateFormat formatD = new SimpleDateFormat("dd");
int dayOfMonthNow = Integer.parseInt(formatD.format(new Date()));
//年龄计算,当大于当前日期就减一岁,小于当前日期就加一岁
ageShow = NowYear - myyear;
if (monthNow <= monthOfYear + 1) {
if (monthNow == monthOfYear + 1) {
if (dayOfMonthNow < dayOfMonth)
ageShow--;
} else {
ageShow--;
}
}
if (ageShow < 0) {
ageShow = 0;
}
if (ageShow <= 65) {
insuredAge.setText(ageShow + "");
} else {
insuredAge.setText("");
showAlert("被保险人不能超过65周岁");
}
}
};
下面是28天前的日期
下面是65周岁前的日期