我有两个编辑文本框,我想验证结束日期,该日期小于开始日期。
我已经完成了简单的验证,因此我应该如何验证,例如,我的开始日期是“ 2019-05-08”,我的结束日期是“ 2019-04-05”,如果结束日期短于错误消息“结束日期小于开始日期”。
这是我的代码:
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;
}
请帮助我,谢谢:)
答案 0 :(得分:1)
您可以执行以下操作比较两个日期:
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;
}
答案 1 :(得分:0)
只需将两个日期转换为Date类型,然后使用Date#getTime()方法进行比较