在Android应用程序中用作DateTime选择器的MaterialDateTimePicker库。需要禁用之前和将来的日期,以便在日历中仅显示3天,即。昨天,今天和明天。除了选择的日期是1个月之后,一切正常。例如,在今天选择(16-05-2017)时,它提前一个月(15-04-2017)。 它显示1个月的回溯日期,而不是1天回来。 代码:
calendar = Calendar.getInstance();
Year = calendar.get(Calendar.YEAR) ;
Month = calendar.get(Calendar.MONTH);
Day = calendar.get(Calendar.DAY_OF_MONTH);
final Calendar maxDate = Calendar.getInstance();
maxDate.set(Calendar.DAY_OF_MONTH, maxDate.get(Calendar.DAY_OF_MONTH) + 1);
maxDate.set(Calendar.MONTH, Month);
maxDate.set(Calendar.YEAR, Year);
final Calendar minDate = Calendar.getInstance();
minDate.set(Calendar.DAY_OF_MONTH, Day - 1);
minDate.set(Calendar.MONTH, Month);
minDate.set(Calendar.YEAR, Year);
mDojBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
datePickerDialog = DatePickerDialog.newInstance(TrainStatus.this, Year, Month, Day);
datePickerDialog.setThemeDark(false);
datePickerDialog.showYearPickerFirst(false);
datePickerDialog.setAccentColor(Color.parseColor("#009688"));
datePickerDialog.setTitle("Select Date");
datePickerDialog.setMinDate(minDate);
datePickerDialog.setMaxDate(maxDate);
datePickerDialog.show(getFragmentManager(), "DatePickerDialog");
}
});
@Override
public void onDateSet(DatePickerDialog view, int Year, int Month, int Day) {
dateSelected = String.valueOf(Year)+String.valueOf(Month)+String.valueOf(Day);
}
感谢任何帮助。谢谢。
答案 0 :(得分:0)
You should add month +1. because here month starts from zero(0).
dateSelected = String.valueOf(Year)+String.valueOf(Month +1)+String.valueOf(Day);
Or
final Calendar calendar = Calendar.getInstance();
int yy = calendar.get(Calendar.YEAR);
int mm = calendar.get(Calendar.MONTH);
int dd = calendar.get(Calendar.DAY_OF_MONTH);
dialog = DatePickerDialog.newInstance(new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
month = monthOfYear;
day = dayOfMonth;
TextView tv = (TextView) v1.findViewById(R.id.txtDate);
tv.setText(new StringBuilder().append(day).append("-")
.append((month + 1)).append("-").append(year));
}
}, yy, mm, dd);
dialog.setMinDate(calendar);
答案 1 :(得分:0)
https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html
检查日历类的官方文档,月份以0开头,表示0 = 1月,11 = 12月。