0

I would like to implement the following behaviour:

  • When today's date is less than 15, 1-15 date is enabled in date Picker
  • When today's date is greater than 15, 16-31 date is enabled in date picker

My code is:

private void DateDialog() {
    final DatePickerDialog dpDialog = new DatePickerDialog(this,android.app.AlertDialog.THEME_DEVICE_DEFAULT_DARK,new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
            cal = Calendar.getInstance();
            cal.setTimeInMillis(System.currentTimeMillis());
            //int curyear = cal.get(Calendar.YEAR);
            cal.set(i, i1, i2);
            etsubmstartdate.setText(dateformatter.format(cal.getTime()));
            selecteddate = dateformatter.format(cal.getTime());
            Log.e("Date of first edit text",selecteddate);
            etsubmstartdate.setText(selecteddate);
        }
    }, year, month, day);
    if (System.currentTimeMillis()<=15)
    {
        dpDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
        long now = System.currentTimeMillis() - 1000;
        dpDialog.getDatePicker().setMaxDate(now+(1000*60*60*24*15));
        dpDialog.show();
    }
    else if(System.currentTimeMillis()>=15)
    {
        dpDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000*60*60*24*2);
        long now = System.currentTimeMillis() - 1000*60*60*24*2;
        dpDialog.getDatePicker().setMaxDate(now+(1000*60*60*24*14));
        dpDialog.show();
    }
}
Bentaye
  • 9,403
  • 5
  • 32
  • 45
RAJ KUMAR
  • 5
  • 1
  • 7
  • 1
    please read again your question, its unclear – Celso Lívero Apr 18 '18 at 10:31
  • Possible duplicate of [How to validate date picker?](https://stackoverflow.com/questions/49895071/how-to-validate-date-picker) – Ole V.V. Apr 18 '18 at 10:32
  • You mean rest of half of the month days will be disabled if the current date is 15. – Farhana Naaz Ansari Apr 18 '18 at 10:35
  • first check your current date, If current date is less than 15 then set min and max date in date picker, It will automatically enable and disabel according to your min and max date. – Farhana Naaz Ansari Apr 18 '18 at 10:38
  • @farhana You mean `dpDialog.getDatePicker.setMinDate()` and `.setMaxDate()`? That sounds viable. But this is already done in the code in the question!? So what are you suggesting?? – Ole V.V. Apr 18 '18 at 16:28

2 Answers2

0

You can use .before and .after methods of Date class.

For example,

if (currentDate.before(yourdate)) {

//write your code require to before current date
}

if (currentDate.after(yourdate)) {

//write your code require to after current date
}

As per your code please replace below code in DateDialog() method

private void DateDialog() {

 final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {

                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear,
                                          int dayOfMonth) {
                        // TODO Auto-generated method stub
                        myCalendar.set(Calendar.YEAR, year);
                        myCalendar.set(Calendar.MONTH, monthOfYear);
                        myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                        updateLabel();
                    }

                };

                DatePickerDialog dpDialog = new DatePickerDialog(MainActivity.this, date, myCalendar
                        .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                        myCalendar.get(Calendar.DAY_OF_MONTH));

                Toast.makeText(MainActivity.this, "date::"+myCalendar.getTimeInMillis(), Toast.LENGTH_SHORT).show();

                String dt = "2018-04-15";
                String dtSixteen = "2018-04-16";

                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
                try {
                    Date dateFifteen = format.parse(dt);
                    Calendar calFifteen = Calendar.getInstance();
                    calFifteen.setTime(dateFifteen);

                    Date dateSixteen = format.parse(dtSixteen);
                    Calendar calSixteen = Calendar.getInstance();
                    calSixteen.setTime(dateSixteen);


                    Date currentDate = myCalendar.getTime();
                    Calendar calendar = Calendar.getInstance();

                    calendar.setTime( myCalendar.getTime() );
                    calendar.set(Calendar.HOUR_OF_DAY, 0);
                    calendar.set(Calendar.MINUTE, 0);
                    calendar.set(Calendar.SECOND, 0);
                    calendar.set(Calendar.MILLISECOND, 0);

                    currentDate = calendar.getTime();


                    if(currentDate.before(dateFifteen) || currentDate.equals(dateFifteen)){
                        dpDialog.getDatePicker().setMaxDate(calFifteen.getTimeInMillis());
                    }else {
                         dpDialog.getDatePicker().setMinDate(calSixteen.getTimeInMillis());
                    }

                } catch (ParseException e) {
                    e.printStackTrace();
                }

                dpDialog.show();

}
Janvi Vyas
  • 732
  • 5
  • 16
0

I haven’t tested, but something like the following.

    ZoneId zone = ZoneId.systemDefault();
    LocalDate today = LocalDate.now(zone);
    LocalDate min;
    LocalDate max;
    if (today.getDayOfMonth() < 16) {
        min = today.withDayOfMonth(1);
        max = today.withDayOfMonth(15);
    } else {
        min = today.withDayOfMonth(16);
        max = today.with(TemporalAdjusters.lastDayOfMonth());
    }

    DatePicker picker = dpDialog.getDatePicker();
    picker.setMinDate(min.atStartOfDay(zone).toInstant().toEpochMilli());
    picker.setMaxDate(max.atStartOfDay(zone).toInstant().toEpochMilli());

    dpDialog.show();

I am using java.time, the modern Java date and time API. While you’re at it, you may substitute your use of the age-old Calendar class and friends with the modern classes too. The modern API is so much nicer to work with.

I am hesitating to use the device time zone setting through ZoneId.systemDefault(), but since the date picker relies on it, I found no way around it. The setting may be changed at any time by another part of your program, leading to unpredictable results.

What went wrong in your code?

Comparing System.currentTimeMillis() to the value 15 won’t work. The method gives you a count of milliseconds since the epoch of January 15, 1970 at 00:00 UTC. Current values are around 1 524 000 000 000. So always much greater than 15.

Whether your time math is correct I haven’t checked. I find it quite cumbersome to do such math myself in the code. I much prefer to leave it to well-tested library methods. It’s much less error-prone it allows for much clearer code.

Question: Can I use java.time on Android?

Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26, I’m told) the modern API comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • Sorry to hear, @RAJKUMAR. If you quote the error message you get, I’ll see if I can figure out what to do about it. – Ole V.V. Apr 19 '18 at 06:57
  • I thought I had, @RAJKUMAR. I don’t have Android Studio, so cannot test and debug. – Ole V.V. Apr 19 '18 at 09:09