I have two edit text box and I want to validate the end date which is less than the start date.
I have done simple validation, so how should I validate for example my Start Date is "2019-05-08" and my End Date is "2019-04-05" and if the end date less than it should give an error message saying "The end date is less than start date" how to do this.
Here is my code:
ExpStDt = (EditText) findViewById(R.id.ExpStDt);
textInputExpStDt = (TextInputLayout)findViewById(R.id.textInputExpStDt);
ExpEndDt = (EditText) findViewById(R.id.ExpEndDt);
textInputExpEndDt = (TextInputLayout)findViewById(R.id.textInputExpEndDt);
if (validate()){
// Get values from edit text fields.
String Exp_St_Dt = ExpStDt.getText().toString();
String Exp_End_Dt = ExpEndDt.getText().toString();
// Data inserted in the database
.......
// This method is used to validate input given by user
String Exp_St_Dt = ExpStDt.getText().toString();
String Exp_End_Dt = ExpEndDt.getText().toString();
// Handling validation for User Name field.
if (Exp_St_Dt.isEmpty()) {
valid = false;
textInputExpStDt.setError("Please Enter The Expected Date Where you want to start Your leave");
textInputExpStDt.requestFocus();
} else {
valid = true;
textInputExpStDt.setError(null);
}
if (Exp_End_Dt.isEmpty()) {
valid = false;
textInputExpEndDt.setError("Please Enter the Expected Date Where you want to End Your leave");
textInputExpEndDt.requestFocus();
} else {
valid = true;
textInputExpEndDt.setError(null);
}
// Check validation for end date that is greater than start date
SimpleDateFormat dfDate = new SimpleDateFormat("yyyy-MM-dd");
boolean b = false;
try {
if(dfDate.parse(Exp_St_Dt).before(dfDate.parse(Exp_End_Dt)))
{
b = true;//If start date is before end date
}
else if(dfDate.parse(Exp_St_Dt).equals(dfDate.parse(Exp_End_Dt)))
{
b = true;//If two dates are equal
}
else if (dfDate.parse(Exp_End_Dt).before(dfDate.parse(Exp_St_Dt)))
{
b = false; //If start date is after the end date
}
} catch (Exception e) {
e.printStackTrace();
}
return valid;
}
Please help me thanks :)
只需将两个日期转换为Date类型,然后使用Date#getTime()方法进行比较
You can do something like this to compare 2 dates:
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.