我需要知道 15 或 30 是否介于2个日期之间。如果我有9月29日和10月1日的情况,这应该是真的,因为它将涵盖9月30日。\
我目前的代码:
SimpleDateFormat formatter = new SimpleDateFormat("MM-dd-yyyy");
Date min = formatter.parse("10-29-2017");
Date max = formatter.parse("11-1-2017");
boolean checker = false;
Calendar cal = Calendar.getInstance();
cal.setTime(min);
int minDay = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(max);
int maxDay = cal.get(Calendar.DAY_OF_MONTH);
for(int i = minDay+1;i<=maxDay;i++){
if(i==15 || i ==30){
checker = true;
}
}
System.out.println(checker);
这是准确的,除非最小值和最大值类似于上面的样本,它将返回false。
我知道了。谢谢你的所有提示。 最终守则:
SimpleDateFormat formatter = new SimpleDateFormat("MM-dd-yyyy");
Date min = formatter.parse("10-29-2017");
Date max = formatter.parse("11-1-2017");
boolean checker = false;
Calendar cal = Calendar.getInstance();
Calendar cal1 = Calendar.getInstance();
cal.setTime(min);
// int minDay = cal.get(Calendar.DAY_OF_MONTH);
cal1.setTime(max);
// int maxDay = cal.get(Calendar.DAY_OF_MONTH);
while(cal.before(cal1) && !checker){
cal.add(Calendar.DAY_OF_MONTH, 1);
if(cal.get(Calendar.DAY_OF_MONTH)==15 || cal.get(Calendar.DAY_OF_MONTH)==30){
checker = true;
}
System.out.println(cal.getTime());
}
System.out.println(checker);
答案 0 :(得分:1)
SimpleDateFormat formatter = new SimpleDateFormat("MM-dd-yyyy");
Date min = formatter.parse("10-29-2017");
Date max = formatter.parse("11-1-2017");
boolean checker = false;
Calendar cal = Calendar.getInstance();
Calendar cal1 = Calendar.getInstance();
cal.setTime(min);
// int minDay = cal.get(Calendar.DAY_OF_MONTH);
cal1.setTime(max);
// int maxDay = cal.get(Calendar.DAY_OF_MONTH);
while(!checker && cal.before(cal1)){
cal.add(Calendar.DAY_OF_MONTH, 1);
if(cal.get(Calendar.DAY_OF_MONTH)==15 || cal.get(Calendar.DAY_OF_MONTH)==30){
checker = true;
}
System.out.println(cal.getTime());
}
System.out.println(checker);
答案 1 :(得分:0)
这是一个关于如何检查日期是否已经过去的示例
static boolean checkDate(int day){
DateFormat dateFormat = new SimpleDateFormat("dd");
Calendar c = Calendar.getInstance();
int daysInMonth = c.getActualMaximum(Calendar.DAY_OF_MONTH);
return day <= daysInMonth;
}
答案 2 :(得分:0)
使用类似的东西。
SimpleDateFormat formatter = new SimpleDateFormat("MM-dd-yyyy");
Date min = formatter.parse("10-29-2017");
Date max = formatter.parse("11-1-2017");
Date d = new Date();
if(d.after(min) && d.before(max)){
System.out.println("in between");
}else{
System.out.println("not in between");
}