我在做Android应用程序。我面临一些问题,以检查当前日期和未来日期。这是我的代码
private void isValidate(String dates) {
calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_MONTH);
int month = calendar.get(Calendar.MONTH);
int year = calendar.get(Calendar.YEAR);
Log.d("profile getCurrent Date ", "" + calendar.getTime());
String currentDate = year + "-" + month + "-" + day;
SimpleDateFormat currentFromat = new SimpleDateFormat(currentDate);
SimpleDateFormat selectedFormat = new SimpleDateFormat(dates);
Log.d("profile dates compare", currentDate + " " + dates);
java.util.Date current, selected;
try {
current = currentFromat.parse(currentDate);
selected = selectedFormat.parse(dates);
int diff = current.compareTo(selected);
if (diff > 0) {
Log.d("profile date status", "Future " + diff);
} else {
Log.d("profile date status", "Past " + diff);
}
if (selected.compareTo(current) > 0) {
Log.d("profile date status", "Future ");
}
if (selected.compareTo(current) < 0) {
Log.d("profile date status ", "Past ");
}
if (selected.compareTo(current) == 0) {
Log.d("profile date status ", "Equal ");
}
if (selected.after(current)) {
Log.d("profile date after", "Future ");
}
if (selected.after(current)) {
Log.d("profile date before ", "Past ");
}
if (selected.after(current)) {
Log.d("profile date equals ", "Equal ");
}
Log.d("profile date format ", currentFromat.format(current) + " "
+ selectedFormat.format(selected));
} catch (ParseException e) {
// TODO Auto-generated catch block
Log.e("profile date error ", "" + e);
}
}
在isValidate(String dates)
以这种格式传递2015-07-23
时。但我无法区分所选日期和当前日期。
答案 0 :(得分:1)
试试这个:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(YOUR DATE STRING);
Calendar now= Calendar.getInstance();
Calendar yourDate = Calendar.getInstance();
yourdate.setTimeMilliseconds(date.getTime);
now.before(yourdate);
要获得实时差异,您可以这样做:
long diff = now.getTimeMilliseconds() - yourdate.getMilliseconds();