gpt4 book ai didi

java - 如何在java中验证这个时间/日期字符串?

转载 作者:行者123 更新时间:2023-11-29 07:12:51 25 4
gpt4 key购买 nike

我有一个格式为的字符串:

8 月 28 日下午 3:00

验证此字符串中是否包含有效时间和有效日期的最佳方法是什么?我的第一个想法是拆分字符串并使用两个正则表达式匹配时间,另一个匹配特定日期格式(缩写月日)。但是,我在使用第二个正则表达式(用于特定日期格式的正则表达式)时遇到了一些麻烦。还有什么方法可以验证字符串的格式是否正确?

最佳答案

你可以试试这个:

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

关于java - 如何在java中验证这个时间/日期字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12168668/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com