安卓比较日期我无法比较两个日期...我参考了很多教程



我正在使用日期选择器对话框,并尝试将当前日期与对话框中指定的日期进行比较。 如果日期早于当前日期,我希望显示无效日期。

当前日期和输入的日期采用相同的格式。 但是我收到错误。 在控制台中打印时,当前日期和输入的日期都采用相同的格式

if(date1.before(currDate))
{
Toast.makeText(getApplicationContext(), "Enter the valid Date", Toast.LENGTH_LONG).show();
}

结果:

当前日期 5/7/2017

取选日期 5-7-2017

试试这个

String strCurrDate = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.YEAR);
String strAnotherDate = "05/03/2017";
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
try {
Date currDate = formatter.parse(strCurrDate);
Date anotherDate = formatter.parse(strAnotherDate);
if (currDate.before(anotherDate)) {
Toast.makeText(getApplicationContext(), "Enter the valid Date", Toast.LENGTH_LONG).show();
}
} catch (ParseException e) {
e.printStackTrace();
}

您可以尝试使用此代码进行日期比较

@SuppressLint("SimpleDateFormat")
public static boolean compareSameDate(String firstDate, String secondDate) {
boolean flag = false;
try {
SimpleDateFormat formatter = new SimpleDateFormat(
"dd/MM/yyyy",
Locale.ENGLISH);
Date date1 = formatter.parse(firstDate);
Date date2 = formatter.parse(secondDate);

if (date2.compareTo(date1) == 0) {
flag = true;
} else if (date2.compareTo(date1) < 0) {
flag = true;
} else {
flag = false;
}
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}

你可以这样尝试,

try {
String currentDateString = "5/7/2017";
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date currDate = formatter.parse(currentDateString);
String pickDateString = "5-7-2017";
formatter = new SimpleDateFormat("dd-MM-yyyy");
Date pickDate = formatter.parse(pickDateString);
if (pickDate.before(currDate)) {
Toast.makeText(getApplicationContext(), "Enter the valid Date", Toast.LENGTH_LONG).show();
}
} catch (ParseException e) {
e.printStackTrace();
}

您可以通过以下方式直接停用日期选择器中的过去日期

datePicker.setMinDate(System.currentTimeMillis() - 1000);

您只能通过以毫秒为单位转换时间来比较时间

Date setDateTime = input.parse(todayTime);
calendar1.setTime(setDateTime);
selectedTime=calendar1.getTimeInMillis();
msTime = System.currentTimeMillis();//current time
//and compare msTime and setsetDateTime 
if (selectedTime>msTime){
//your logic
}

或者您可以通过仅以数字格式格式化日期格式来直接比较日期,例如 对于 5-7-2017 是572017并将其与相同格式的选定日期进行比较

最新更新