Java:检查当前字符串的日期格式是否符合要求的格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20231539/
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
Java: Check the date format of current string is according to required format or not
提问by Elvin
I wanted to know that is there any method available in Javathat can do this.Otherwise I may go for Regex solution.
I have input string from user that can be any characters. And I want to check that the input string is according to my required date format or not.
我想知道Java中是否有任何可用的方法可以做到这一点。否则我可能会选择 Regex 解决方案。
我有来自用户的输入字符串,可以是任何字符。我想检查输入字符串是否符合我所需的日期格式。
As I have input 20130925and my required format is dd/MM/yyyyso, for this case I should get false.
I don't want to convert this date I just want to check whether input string is according to required date format or not.
因为我输入了20130925并且我需要的格式是dd/MM/yyyy所以,对于这种情况,我应该得到false。
我不想转换这个日期我只想检查输入字符串是否符合所需的日期格式。
I have tried following
我试过跟随
Date date = null;
try {
date = new SimpleDateFormat("dd/MM/yyyy").parse("20130925");
} catch (Exception ex) {
// do something for invalid dateformat
}
but my catch (Exception ex) block is unable to catch any exceptions generated by SimpleDateFormat.Parse();
但是我的 catch (Exception ex) 块无法捕获 SimpleDateFormat.Parse() 生成的任何异常;
回答by Baby
For your case, you may use regex:
对于您的情况,您可以使用正则表达式:
boolean checkFormat;
if (input.matches("([0-9]{2})/([0-9]{2})/([0-9]{4})"))
checkFormat=true;
else
checkFormat=false;
For a larger scope or if you want a flexible solution, refer to MadProgrammer'sanswer.
对于更大的范围或者如果您想要灵活的解决方案,请参阅MadProgrammer 的答案。
Edit
编辑
Almost 5 years after posting this answer, I realize that this is a stupid way to validate a date format. But i'll just leave this here to tell people that using regex to validate a date is unacceptable
发布此答案近 5 年后,我意识到这是验证日期格式的愚蠢方法。但我会留在这里告诉人们使用正则表达式来验证日期是不可接受的
回答by MadProgrammer
Disclaimer
免责声明
Parsing a string back to date/time value in an unknown format is inherently impossible (let's face it, what does 3/3/3
actually mean?!), all we can do is "best effort"
将字符串解析回未知格式的日期/时间值本质上是不可能的(让我们面对现实,这3/3/3
实际上意味着什么?!),我们所能做的就是“尽力而为”
Important
重要的
This solution doesn'tthrow an Exception
, it returns a boolean
, this is by design. Any Exception
s are used purely as a guard mechanism.
此解决方案不会抛出Exception
,而是返回boolean
,这是设计使然。任何Exception
s 纯粹用作保护机制。
2018
2018年
Since it's now 2018 and Java 8+ has the date/time API (and the rest have the ThreeTen backport). The solution remains basically the same, but becomes slightly more complicated, as we need to perform checks for:
由于现在是 2018 年,Java 8+ 具有日期/时间 API(其余的具有ThreeTen backport)。解决方案基本保持不变,但稍微复杂一些,因为我们需要执行以下检查:
- date and time
- date only
- time only
- 日期和时间
- 仅限日期
- 仅限时间
This makes it look something like...
这使它看起来像......
public static boolean isValidFormat(String format, String value, Locale locale) {
LocalDateTime ldt = null;
DateTimeFormatter fomatter = DateTimeFormatter.ofPattern(format, locale);
try {
ldt = LocalDateTime.parse(value, fomatter);
String result = ldt.format(fomatter);
return result.equals(value);
} catch (DateTimeParseException e) {
try {
LocalDate ld = LocalDate.parse(value, fomatter);
String result = ld.format(fomatter);
return result.equals(value);
} catch (DateTimeParseException exp) {
try {
LocalTime lt = LocalTime.parse(value, fomatter);
String result = lt.format(fomatter);
return result.equals(value);
} catch (DateTimeParseException e2) {
// Debugging purposes
//e2.printStackTrace();
}
}
}
return false;
}
This makes the following...
这使得以下...
System.out.println("isValid - dd/MM/yyyy with 20130925 = " + isValidFormat("dd/MM/yyyy", "20130925", Locale.ENGLISH));
System.out.println("isValid - dd/MM/yyyy with 25/09/2013 = " + isValidFormat("dd/MM/yyyy", "25/09/2013", Locale.ENGLISH));
System.out.println("isValid - dd/MM/yyyy with 25/09/2013 12:13:50 = " + isValidFormat("dd/MM/yyyy", "25/09/2013 12:13:50", Locale.ENGLISH));
System.out.println("isValid - yyyy-MM-dd with 2017-18--15 = " + isValidFormat("yyyy-MM-dd", "2017-18--15", Locale.ENGLISH));
output...
输出...
isValid - dd/MM/yyyy with 20130925 = false
isValid - dd/MM/yyyy with 25/09/2013 = true
isValid - dd/MM/yyyy with 25/09/2013 12:13:50 = false
isValid - yyyy-MM-dd with 2017-18--15 = false
Original Answer
原答案
Simple try and parse the String
to the required Date
using something like SimpleDateFormat
简单的尝试使用类似的东西解析String
到所需的Date
SimpleDateFormat
Date date = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
date = sdf.parse(value);
if (!value.equals(sdf.format(date))) {
date = null;
}
} catch (ParseException ex) {
ex.printStackTrace();
}
if (date == null) {
// Invalid date format
} else {
// Valid date format
}
You could then simply write a simple method that performed this action and returned true
when ever Date
was not null...
然后,您可以简单地编写一个简单的方法来执行此操作并true
在Date
不为空时返回...
As a suggestion...
作为建议...
Updated with running example
更新了运行示例
I'm not sure what you are doing, but, the following example...
我不确定你在做什么,但是,下面的例子......
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestDateParser {
public static void main(String[] args) {
System.out.println("isValid - dd/MM/yyyy with 20130925 = " + isValidFormat("dd/MM/yyyy", "20130925"));
System.out.println("isValid - dd/MM/yyyy with 25/09/2013 = " + isValidFormat("dd/MM/yyyy", "25/09/2013"));
System.out.println("isValid - dd/MM/yyyy with 25/09/2013 12:13:50 = " + isValidFormat("dd/MM/yyyy", "25/09/2013 12:13:50"));
}
public static boolean isValidFormat(String format, String value) {
Date date = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
date = sdf.parse(value);
if (!value.equals(sdf.format(date))) {
date = null;
}
} catch (ParseException ex) {
ex.printStackTrace();
}
return date != null;
}
}
Outputs (something like)...
输出(类似)...
java.text.ParseException: Unparseable date: "20130925"
isValid - dd/MM/yyyy with 20130925 = false
isValid - dd/MM/yyyy with 25/09/2013 = true
isValid - dd/MM/yyyy with 25/09/2013 12:13:50 = false
at java.text.DateFormat.parse(DateFormat.java:366)
at javaapplication373.JavaApplication373.isValidFormat(JavaApplication373.java:28)
at javaapplication373.JavaApplication373.main(JavaApplication373.java:19)
Not correct. For isValidFormat("yyyy-MM-dd", "2017-18--15"); not throw any Exception.
不正确。对于 isValidFormat("yyyy-MM-dd", "2017-18--15"); 不抛出任何异常。
isValid - yyyy-MM-dd", "2017-18--15 = false
Seems to work as expected for me - the method doesn't rely on (nor does it throw) the exception alone to perform it's operation
似乎对我来说按预期工作 - 该方法不依赖(也不抛出)单独的异常来执行它的操作
回答by jAnA
You can try this to simple date format valdation
你可以试试这个简单的日期格式验证
public Date validateDateFormat(String dateToValdate) {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HHmmss");
//To make strict date format validation
formatter.setLenient(false);
Date parsedDate = null;
try {
parsedDate = formatter.parse(dateToValdate);
System.out.println("++validated DATE TIME ++"+formatter.format(parsedDate));
} catch (ParseException e) {
//Handle exception
}
return parsedDate;
}
回答by tiwari.vikash
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
formatter.setLenient(false);
try {
Date date= formatter.parse("02/03/2010");
} catch (ParseException e) {
//If input date is in different format or invalid.
}
formatter.setLenient(false) will enforce strict matching.
formatter.setLenient(false) 将强制执行严格匹配。
If you are using Joda-Time -
如果您使用 Joda-Time -
private boolean isValidDate(String dateOfBirth) {
boolean valid = true;
try {
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy");
DateTime dob = formatter.parseDateTime(dateOfBirth);
} catch (Exception e) {
valid = false;
}
return valid;
}
回答by Pramit
A combination of the regex and SimpleDateFormat is the right answer i believe. SimpleDateFormat does not catch exception if the individual components are invalid meaning, Format Defined: yyyy-mm-dd input: 201-0-12 No exception will be thrown.This case should have been handled. But with the regex as suggested by Sok Pomaranczowy and Baby will take care of this particular case.
我相信正则表达式和 SimpleDateFormat 的组合是正确的答案。如果单个组件无效,则 SimpleDateFormat 不捕获异常含义, Format Defined: yyyy-mm-dd input: 201-0-12 不会抛出异常。这种情况应该已经处理了。但是使用 Sok Pomaranczowy 和 Baby 建议的正则表达式会处理这个特殊情况。
回答by Alberto Cerqueira
Here's a simple method:
这是一个简单的方法:
public static boolean checkDatePattern(String padrao, String data) {
try {
SimpleDateFormat format = new SimpleDateFormat(padrao, LocaleUtils.DEFAULT_LOCALE);
format.parse(data);
return true;
} catch (ParseException e) {
return false;
}
}
回答by Tonmoy
Regex can be used for this with some detailed info for validation, for example this code can be used to validate any date in (DD/MM/yyyy) format with proper date and month value and year between (1950-2050)
正则表达式可用于此,并带有一些详细的验证信息,例如此代码可用于验证 (DD/MM/yyyy) 格式的任何日期,并具有适当的日期和月份值以及 (1950-2050) 之间的年份
public Boolean checkDateformat(String dateToCheck){
String rex="([0]{1}[1-9]{1}|[1-2]{1}[0-9]{1}|[3]{1}[0-1]{1})+
\/([0]{1}[1-9]{1}|[1]{1}[0-2]{2})+
\/([1]{1}[9]{1}[5-9]{1}[0-9]{1}|[2]{1}[0]{1}([0-4]{1}+
[0-9]{1}|[5]{1}[0]{1}))";
return(dateToCheck.matches(rex));
}
回答by kksal55
For example, if you want the date format to be "03.11.2017"
例如,如果您希望日期格式为“03.11.2017”
if (String.valueOf(DateEdit.getText()).matches("([1-9]{1}|[0]{1}[1-9]{1}|[1]{1}[0-9]{1}|[2]{1}[0-9]{1}|[3]{1}[0-1]{1})" +
"([.]{1})" +
"([0]{1}[1-9]{1}|[1]{1}[0-2]{1}|[1-9]{1})" +
"([.]{1})" +
"([20]{2}[0-9]{2})"))
checkFormat=true;
else
checkFormat=false;
if (!checkFormat) {
Toast.makeText(getApplicationContext(), "incorrect date format! Ex.23.06.2016", Toast.LENGTH_SHORT).show();
}