7
votes

Date de fin supérieure à la validation de la date de début Android

J'ai deux EditText's. Un avec date de début et autre avec la date de fin. J'ai besoin de faire une validation et de vérifier si la date de fin est supérieure à la date de début. Je ne sais pas comment je peux faire cela.

Dans mon code, je fais la différence entre deux dates dans des jours et je dois maintenant vérifier si la date de fin est supérieure à la date de début p>

Voici mon code: P>

             //EditText with string of start date
            dataInicio = (EditText)findViewById(R.id.ses_dpDataIni);
             //EditText with string of end date
    dataFim = (EditText)findViewById(R.id.ses_dpDataFim);

             //Convert String to calendar to check the difference between two dates..
    try{
    dateInic = dataInicio.getText().toString();
    dateFim = dataFim.getText().toString();

    calInic=Calendar.getInstance();
    calFim = Calendar.getInstance();
    calInic.setTime(form.parse(dateInic));
    calFim.setTime(form.parse(dateFim));
    }
     catch (ParseException e) { 
         e.printStackTrace(); 
    } 
    Log.w(SessaoQuotaEdit.class.getName(),"DIFERENCA DE DIAS"  +daysBetween(calInic,calFim));
    tvDiasQuotas = (TextView)findViewById(R.id.ses_tvNumDiasQuota);
    tvDiasQuotas.setText("NUMBER OF DAYS: " +daysBetween(calInic,calFim));

            //CHECK IS END-DATE IS GREATER THAN START-DATE
             .............
             .............


0 commentaires

10 Réponses :


4
votes

Essayez cette fonction.

public static boolean isDateAfter(String startDate,String endDate)
    {
        try
        {
            String myFormatString = "yyyy-M-dd"; // for example
            SimpleDateFormat df = new SimpleDateFormat(myFormatString);
            Date date1 = df.parse(endDate));
            Date startingDate = df.parse(startDate);

            if (date1.after(startingDate))
                return true;
            else
                return false;
        }
        catch (Exception e) 
        {

            return false;
        }
    }


0 commentaires

0
votes

Pourquoi ne pas essayer DAINTUTILS.GETRELATIVÉTIVESPANSTRING ?


0 commentaires

23
votes
SimpleDateFormat dfDate  = new SimpleDateFormat("yyyy-MM-dd");
public static boolean checkDates("2012-07-12", "2012-06-12)"    {
    boolean b = false;
    try {
        if(dfDate.parse(d1).before(dfDate.parse(d2)))
        {
            b = true;//If start date is before end date
        }
        else if(dfDate.parse(d1).equals(dfDate.parse(d2)))
        {
            b = true;//If two dates are equal
        }
        else
        {
            b = false; //If start date is after the end date
        }
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return b;
}

2 commentaires

Merci, tu sauve ma journée.


J'utilise Kotlin et le mien continue de me donner l'exception. pouvez-vous s'il vous plaît aidez-moi?



0
votes

Merci à tout le monde ....

Here is my solution

        if(calInic.after(calFim)==true)
        Log.w(SessaoQuotaEdit.class.getName(),"ERROR: DATA FINAL É ANTES DA DATA INICIAL");
    else
        if(calInic.before(calFim)==true)
            Log.w(SessaoQuotaEdit.class.getName(),"CORRECTO: DATAS CORRECTAS");
        else
            if(calInic.equals(calFim)==true)
                Log.w(SessaoQuotaEdit.class.getName(),"CORRECTO: DATAS IGUAIS");


0 commentaires

0
votes
***Used Ram kiran Answer***     

public boolean checkDatesBefore(String startDate, String endDate) {
            boolean b = false;
            SimpleDateFormat dfDate = new SimpleDateFormat("MM/dd/yyyy");
            try {
                if (dfDate.parse(startDate).before(dfDate.parse(endDate))) {
                    b = true;// If start date is before end date
                } else if (dfDate.parse(startDate).equals(dfDate.parse(endDate))) {
                    b = true;// If two dates are equal
                } else {
                    b = false; // If start date is after the end date
                }
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return b;
        }

    checkDatesBefore(startDate,endDate);


    **and check another time for not less than or equals today**

    public boolean checkDatesAfter(String selectedDate, String today) {
            boolean b = false;
            SimpleDateFormat dfDate = new SimpleDateFormat("MM/dd/yyyy");
            try {
                if (dfDate.parse(selectedDate).compareTo((dfDate.parse(today))) < 0)

           {
                    b = true;// If start date is before end date
                } else if (dfDate.parse(selectedDate).equals(dfDate.parse(today))) {
                    b = true;// If two dates are equal
                } else {
                    b = false; // If start date is after the end date
                }
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return b;
        }
        enter code here

    call checkDatesAfter(selectedDate,today)

    **Best of luck..**

0 commentaires

0
votes
if (!dateValidation("2016-11-23", "2016-11-24", "yyyy-MM-dd")) {
    // ToastHelper.show("Please select date properly");

    // or do something
}


public static boolean dateValidation(String startDate,String endDate,String dateFormat )
{
    try
    {

        SimpleDateFormat df = new SimpleDateFormat(dateFormat);
        Date date1 = df.parse(endDate);
        Date startingDate = df.parse(startDate);

        if (date1.after(startingDate))
            return true;
        else
            return false;
    }
    catch (Exception e)
    {
        return false;
    }
}

0 commentaires

0
votes

réponse simplifiée de RAM Kiran , il enregistrera uniquement une instruction. xxx


0 commentaires

1
votes
public static boolean CheckDates(String d1, String d2){
    SimpleDateFormat dfDate  = new SimpleDateFormat("yyyy-MM-dd");
    boolean b = false;
    try {
        if(dfDate.parse(d1).before(dfDate.parse(d2)))
        {
            b = true;//If start date is before end date
        }
        else if(dfDate.parse(d1).equals(dfDate.parse(d2)))
        {
            b = true;//If two dates are equal
        }
        else
        {
            b = false; //If start date is after the end date
        }
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return b;
}

1 commentaires

Certaines explications ou commentaires de code amélioreraient la réponse.



0
votes

extension de kotlin: xxx


0 commentaires

0
votes
          Calendar startdate = Calendar.getInstance();
            Calendar enddate = Calendar.getInstance();
                  imgstartcal1.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                fromDatePickerDialog = new DatePickerDialog(mainActivity, new DatePickerDialog.OnDateSetListener() {
                                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {


                                        startdate.set(year, monthOfYear, dayOfMonth);
                                        edtstartdate.setText(dateFormatter.format(startdate.getTime()));
                                       edtenddate.setText(null);

                                    }
                                }, startdate.get(Calendar.YEAR), startdate.get(Calendar.MONTH), startdate.get(Calendar.DAY_OF_MONTH));
                                fromDatePickerDialog.show();
                            }
                        });

          imgendcal1.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View view) {
          fromDatePickerDialog = new DatePickerDialog(mainActivity, new DatePickerDialog.OnDateSetListener() {
          public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

          enddate.set(year, monthOfYear, dayOfMonth);
          if (startdate.after(enddate) || enddate.equals(startdate)){                                
          edtenddate.getText().toString().equals(null);
          }else{                                                  
    fromDatePickerDialog.getDatePicker().setMinDate(startdate.getInstance().getTimeInMillis());                                              
          edtenddate.setText(dateFormatter.format(enddate.getTime()));
            }
            }
  }, enddate.get(Calendar.YEAR), startdate.get(Calendar.MONTH),startdate.get(Calendar.DAY_OF_MONTH));
    fromDatePickerDialog.show();
    }
   });

1 commentaires

Bien que cette extrait de code puisse résoudre le problème, cela n'explique pas pourquoi ni comment il répond à la question. S'il vous plaît Inclure une explication de votre code , car cela aide vraiment à améliorer la qualité de votre message. N'oubliez pas que vous répondez à la question des lecteurs à l'avenir, et ces personnes pourraient ne pas connaître les raisons de votre suggestion de code.