Java 如何验证字符串是否为 YYYYMMDD 格式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21975567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to validate a String whether it is in YYYYMMDD format?
提问by
I have a string which is being passed to one of my method in the form of YYYYMMDD
-
我有一个字符串,它以以下形式传递给我的方法之一YYYYMMDD
-
public static void verifyInput(String input) {
}
Here input passed will be in this form "YYYYMMDD";
这里传递的输入将采用这种形式“YYYYMMDD”;
How do I validate whether input
String which is passed in this form YYYYMMDD
only?
如何验证是否仅以input
这种形式传递的字符串YYYYMMDD
?
I just need to validate whether it is in YYYYMMDD
this format.. I don't need to get the current date in this YYYYMMDD
format and then compare it with ss
.
我只需要验证它是否是YYYYMMDD
这种格式。我不需要以这种YYYYMMDD
格式获取当前日期,然后将其与ss
.
UPDATE:-
更新:-
I just need to validate the string input to see whether they are in this format YYYYMMDD
我只需要验证字符串输入,看看它们是否是这种格式 YYYYMMDD
Meaning if anyone is passing a String hello
then it is not in this YYYYMMDD
format..
意思是如果有人传递一个字符串,hello
那么它不是这种YYYYMMDD
格式..
And if anyone is passing this String 20130130
then this gets validated as it is in this YYYYMMDD
format..
如果有人正在传递这个字符串,20130130
那么它就会按照这种YYYYMMDD
格式进行验证..
采纳答案by Elliott Frisch
You can use SimpleDateFormatand Date, here is one solution -
您可以使用SimpleDateFormat和Date,这是一种解决方案 -
private static final java.text.SimpleDateFormat sdf =
new java.text.SimpleDateFormat("yyyyMMdd");
public static java.util.Date verifyInput(String input) {
if (input != null) {
try {
java.util.Date ret = sdf.parse(input.trim());
if (sdf.format(ret).equals(input.trim())) {
return ret;
}
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
public static void main(String[] args) {
String[] dates = new String[] { "20141031",
"20130228", "20000229", "20000230" };
for (String str : dates) {
System.out.println(verifyInput(str));
}
}
Outputs
输出
Fri Oct 31 00:00:00 EDT 2014
Thu Feb 28 00:00:00 EST 2013
Tue Feb 29 00:00:00 EST 2000
null
回答by PaulJWilliams
Pass it into a SImpleDateFormat object for format string yyyyMMdd.
将其传递到格式字符串 yyyyMMdd 的 SImpleDateFormat 对象中。
回答by Ima Miri
Convert String to Date:
将字符串转换为日期:
SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMDD");
Date date = sdf.parse(input);
回答by B.J. Smegma
try {
new SimpleDateFormat("yyyyDDmm").parse(input);
// good format
} catch (ParseException e) {
// bad format
}
回答by Johannes H.
Using RegExp (Pattern& Matcher):
public static void verifyInput(String input) {
Pattern p = Pattern.compile("^\d{4}(1[012]|0[1-9])(3[01]|[12]\d|0[0-9])$");
Matcher m = p.matcher(input);
return m.matches();
}
(While it does check for valid month and day nubmers, it doesn't check if the current month only has 28/30 days. thatn can be added though if you need to check it.)
(虽然它会检查有效的月份和日期数字,但它不会检查当前月份是否只有 28/30 天。如果您需要检查,可以添加。)
回答by Devavrata
you can validate it through..
你可以通过..
boolean validate(String s)
{
if(s.length()!=8)
return false;
try{
int year=Integer.parseInt(s.substring(0,4));
}
catch(Exception e)
{
return false;
}
try{
int month=Integer.parseInt(s.substring(4,6));
}
catch(Exception e)
{
return false;
}
try{
int date=Integer.parseInt(s.substring(6,8));
}
catch(Exception e)
{
return false;
}
if(month>12)
return false;
if(date>31)
return false;
return true;
}
回答by Hot Licks
To expand on Neuron's answer:
扩展神经元的答案:
if (month < 1 || month > 12)
return false;
int days = 30;
if (month == 2) {
days = 28;
if ((year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0))) days = 29;
}
else {
if ((1 << month) & 0x15A2) days = 31;
}
if (date < 1 || date > days)
return false;
return true;
回答by Paul J Abernathy
You could do something like this:
你可以这样做:
private boolean validateDateFormat(String input) {
if(input == null) {
return false;
}
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
try {
Date d = format.parse(input);
logger.debug(d);
return true;
} catch(ParseException e) {
return false;
}
}
Unit testing it with this method:
使用此方法对其进行单元测试:
@Test
public void TestDateValidation() {
logger.info("\ntestDateValidation()");
assertEquals(false, validateDateFormat("hello"));
assertEquals(false, validateDateFormat(null));
assertEquals(false, validateDateFormat(""));
assertEquals(false, validateDateFormat("d20140228"));
assertEquals(false, validateDateFormat("Feb 28, 2014"));
assertEquals(true, validateDateFormat("20140228"));
validateDateFormat("20140229");
validateDateFormat("2014024000");
}
gives this output:
给出这个输出:
Fri Feb 28 00:00:00 EST 2014
Sat Mar 01 00:00:00 EST 2014
Mon Jan 13 00:00:00 EST 2025
Unfortunately, those two wacky dates are still parsed as if they were real dates, but it looks like that is not a problem based on your requirements.
不幸的是,这两个古怪的日期仍然被解析为好像它们是真实的日期,但根据您的要求,这看起来不是问题。