如何在java中验证这个时间/日期字符串? [英] how to verify this time/date string in java?

查看:399
本文介绍了如何在java中验证这个时间/日期字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的字符串格式为:

8月28日下午3:00

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?

推荐答案

你可以试试这个:

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

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

这篇关于如何在java中验证这个时间/日期字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆