用户使用年,月,日下拉菜单选择日期。我必须将用户输入的日期与今天的日期进行比较。基本上看看他们是否是同一个日期。例如 用户输入了02/16/2012。如果今天是02/16/2012,那么我必须显示一条消息。我该怎么做? 我尝试使用毫秒,但这会产生错误的结果。
答案 0 :(得分:0)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = sdf.parse("2012-05-17");
Date date2 = sdf.parse("2012-01-01");
System.out.println(sdf.format(date1));
System.out.println(sdf.format(date2));
if(date1.compareTo(date2)>0){
System.out.println("Date1 is after Date2");
}else if(date1.compareTo(date2)<0){
System.out.println("Date1 is before Date2");
}else if(date1.compareTo(date2)==0){
System.out.println("Date1 is equal to Date2");
}
或
if(date1.equals(date2)){
System.out.println("Date1 is equal Date2");
}
答案 1 :(得分:0)
你回来了什么样的对象?字符串,日历,日期?您可以获取该字符串并进行比较,至少您认为您在订购时遇到问题YYYY MM DD /// DD MM YYY在这种情况下我建议根据您的规格YYYYMMDD创建自定义字符串然后比较它们。
Date d1 = new Date();
Date d2 = new Date();
String day1 = d1.getYear()+"/"+d1.getMonth()+"/"+d1.getDate();
String day2 = d2.getYear()+"/"+d2.getMonth()+"/"+d2.getDate();
if(day1.equals(day2)){
System.out.println("Same day");
}
答案 2 :(得分:0)
java中的日期是时刻,分辨率为“毫秒”。要有效地比较两个日期,您需要首先将两个日期设置为小时,分钟,秒和毫秒的“同一时间”。 java.util.Date
中的所有“setTime”方法都已被删除,因为它们无法正常用于国际化和本地化问题。
为了“修复”这个问题,我们引入了一个新课程GregorianCalendar
GregorianCalendar cal1 = new GregorianCalendar(2012, 11, 17);
GregorianCalendar cal2 = new GregorianCalendar(2012, 11, 17);
return cal1.equals(cal2); // will return true
GregorianCalendar工作的原因与年,月,日构造函数中的小时,分钟,秒和毫秒初始化为零有关。您可以尝试使用java.util.Date
之类的已弃用的方法,使用setHours(0)
进行近似。但是,由于缺少setMillis(0)
,最终会失败。这意味着要使用Date
格式,您需要获取毫秒并执行一些整数数学运算来将毫秒设置为零。
date1.setHours(0);
date1.setMinutes(0);
date1.setSeconds(0);
date1.setTime((date1.getTime() / 1000L) * 1000L);
date2.setHours(0);
date2.setMinutes(0);
date2.setSeconds(0);
date2.setTime((date2.getTime() / 1000L) * 1000L);
return date1.equals(date2); // now should do a calendar date only match
相信我,只需使用Calendar / GregorianCalendar类,它就是前进的方向(直到Java采用更复杂的东西,比如joda时间。
答案 3 :(得分:0)
有两种方法可以做到。第一个是格式化相同日期格式的日期或以字符串格式处理日期。
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String date1 = sdf.format(selectedDate);
String date2 = sdf.format(compareDate);
if(date1.equals(date2)){
}else{
}
或
Calendar toDate = Calendar.getInstance();
Calendar nowDate = Calendar.getInstance();
toDate.set(<set-year>,<set-month>,<set-date->);
if(!toDate.before(nowDate))
//display your report
else
// don't display the report
答案 4 :(得分:0)
以上答案是正确的,但考虑使用JodaTime - 它更简单直观的API。
您可以使用DateTime
方法设置with*
并进行比较。
看看这个answer