如何在指定的日期范围内找到给定的日期

How to find the given date is with in specified date range

这是我的代码

boolean isWithinRange(String d)
{
    boolean withinDate = false;   
    try
    {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = dateFormat.parse(d);
        withinDate = !(date.before(startDate) || date.after(endDate));
    }
    catch (ParseException parseException)
    {
     }
    return withinDate;
}

输入

2015-11-26
2015-11-26 - 复制

两者都返回 true 但我需要的是“2015-11-26”应该是 true 而“2015-11-26 - Copy”应该是 false。

这是因为SimpleDateFormat愉快地解析了“2015-11-26”而忽略了“-Copy”部分。

javadoc 状态:

Parses text from the beginning of the given string to produce a date. The method may not use the entire text of the given string.

要检测是否使用了整个字符串,请改用 parse(String source, ParsePosition pos) 方法。 ParsePosition 告诉您解析停止的位置。只需将其与原始日期字符串的长度进行比较即可。

这里的问题是我们正在传递日期格式 'yyyy-MM-dd'。这将验证此格式的给定输入。

例如,

static boolean isWithinRange(String d)
{
    boolean withinDate = false;   
    try
    {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date date = dateFormat.parse(d);
        withinDate = !(date.before(startDate) || date.after(endDate));
    }
    catch (ParseException parseException)
    {
        parseException.printStackTrace();
     }
    return withinDate;
}

以上代码抛出异常,因为我们将日期格式传递为 'yyyy-MM-dd hh:mm:ss'。所以这将找到小时分钟和秒

public static void main(String[] args) {
    isWithinRange("2015-12-11 - Copy");
    isWithinRange("2015-12-11");

}

public static boolean isWithinRange(String d) {
    boolean withinDate = false;
    try {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dd = d.indexOf(" ") !=-1 ? d.substring(0, d.indexOf(" ")) : d; // Find valid String 
        if(d.equals(dd)){
        Date date = dateFormat.parse(d);
        withinDate = !(date.before(startDate)) || date.after(endDate)));
        }else{
            withinDate =false;
        }
    } catch (ParseException parseException) {
    }
    return withinDate;
}

在测试之前先测试大小是否为 10:

if (d.length!10) return false;