0

我需要实现输入日期(如 SEP 2014、OCT 2014、NOV 2014 等)是否为当前月份的逻辑。我已经写了下面的逻辑来检查选定的一周是否是当前的一周,使用下面的方法但不能在当前月份实现

public static boolean isCurrentWeek(Date date, Date dateStart, Date dateEnd)

 {

    if (date != null && dateStart != null && dateEnd != null) {


        if(date.equals(dateStart) || date.equals(dateEnd) ){


            return true;


        }else if (date.after(dateStart) && date.before(dateEnd)) {


            return true;


        }


        else {


            return false;

        }

    }
    return false;
}
4

2 回答 2

1

为此尝试 Apache Commons:

DateUtils.truncatedEquals( date, new Date(), Calendar.MONTH );

true如果两个日期在同一个月,则返回。

编辑

也许是这样:

public static boolean isInCurrentMonth(String inputDateString) {
    SimpleDateFormat sdf = new SimpleDateFormat("MMM yyyy", Locale.ENGLISH);
    try {
        Date inputDate = sdf.parse(inputDateString);
        return DateUtils.truncatedEquals(new Date(), inputDate, Calendar.MONTH);
    } catch (ParseException e) {
        // error handling
    }
}
于 2014-10-03T14:06:10.547 回答
0

我认为您可以使用类似于此的代码来解决您的问题:

String target = "Oct 2000";
DateFormat df = new SimpleDateFormat("MMM yyyy", Locale.ENGLISH);
try{
  Date date = df.parse(target);
  Calendar calendar = Calendar.getInstance();
  Calendar targetCalendar = Calendar.getInstance();
  targetCalendar.setTime(date);
  System.out.println(targetCalendar.get(Calendar.MONTH) == calendar.get(Calendar.MONTH));
 } catch (ParseException e){
 }

字符串target是您的输入,例如“Sep 2014”。此字符串被解析为 aDate然后用于设置Calendar对象中的时间。第二个Calendar包含当前时间。检查两个日历是否在他们的月份匹配完成是System.out.println调用。

于 2014-10-03T14:31:11.970 回答