2012-08-28 82 views
1

我在的格式的字符串:08月28如何在java中验证这个时间/日期字符串?

下午3:00什么是验证一个有效的时间和有效日期包含在此字符串中的最佳方式是什么?我的第一个想法是分割字符串,并使用两个正则表达式匹配一个时间,另一个匹配特定日期格式(缩写月份日)。然而,我对第二个正则表达式(specfic日期格式的那个)有点麻烦。如何验证字符串是否有正确的格式?

回答

3

你可以试试这个:

public boolean isValid(String dateStr) { 

    // K: hour of the day in am/pm 
    // m: minute of a hour 
    // 'on': static text 
    // MMM: name of the month with tree letters 
    // dd: day of the month (you can use just d too) 
    DateFormat df = new SimpleDateFormat("K:m a 'on' MMM dd", Locale.US); 

    try { 
     df.parse(dateStr); 
     return true; 
    } catch (ParseException exc) { 
    } 

    return false; 

} 

更多格式字符串在这里:http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

2

使用java.text.SimpleDateFormat。使用格式字符串,如HH:mm aa 'on' MMM dd

您可能必须将yyyy添加到格式字符串中,并将2012添加到输入中。

+0

我认为他是试图检查预先存在的字符串是否有效,而不是创建新的日期字符串。如我错了请纠正我。 – arshajii

+0

只需要用你的字符串调用'parse()',如果它不符合格式,就会抛出'ParseException'。您可以免费获得返回的“日期”!你可能想把'isLenient'设置为'false'。如果要确保使用了整个输入字符串,请使用“parse”的双参数形式。 –

1

使用SimpleDateFormat并确保它不使用lenient解析:

try { 
    DateFormat df = new SimpleDateFormat("h:mm a 'on' MMM dd", Locale.US); 
    df.setLenient(false); 
    Date dt = df.parse(s); 
} catch (ParseException pe) { 
    // Wrong format 
} 
+0

对不起João,我没有看到你的答案。 – davidbuzatto