how to verify this time/date string in java?

折月煮酒 提交于 2019-12-11 08:17:52

问题


I have a string in the format of:

3:00 pm on Aug 28

What would be the best way to verify that a valid time and valid date is contained within this string? My first thought was to split the string and use two regexs to match a time and the other one to match that specfic date format (abbreviate month day). However I'm having a little bit of trouble with the second regex (the one for the specfic date format). How else could one go about verifying the string is in the correct format?


回答1:


You can try this:

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;

}

More about the format string here: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html




回答2:


Use java.text.SimpleDateFormat. Use a format string something like HH:mm aa 'on' MMM dd.

You may have to add yyyy to the format string and 2012 to your input.




回答3:


Use SimpleDateFormat and make sure it doesn't use lenient parsing:

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
}


来源:https://stackoverflow.com/questions/12168668/how-to-verify-this-time-date-string-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!