我正在使用datepicker对话框,并尝试将当前日期与对话框中指定的日期进行比较。 如果日期在当前日期之前,我希望显示无效日期。
输入的当前日期和日期格式相同。但我收到了错误。在控制台中打印时,当前日期和输入日期的格式相同
if(date1.before(currDate))
{
Toast.makeText(getApplicationContext(), "Enter the valid Date", Toast.LENGTH_LONG).show();
}
结果:
当前日期5/7/2017
选择日期5-7-2017
答案 0 :(得分:1)
试试这个
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();
}
答案 1 :(得分:0)
您可以通过
直接停用datepicker中的过去日期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并将其与相同格式的选定日期进行比较
答案 2 :(得分:0)
您可以尝试使用此代码进行日期比较
@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;
}
答案 3 :(得分:0)
你可以这样试试,
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();
}