java - 如何使用java检查像“08-Nov-2011”这样的字符串是否是有效日期?
问题描述
我想检查输入字符串是否为有效日期。字符串就像:-
"08-Nov-2011"
"21 Mar 2019"
爪哇代码:-
boolean checkFormat;
String input = "08-Nov-2011";
if (input.matches("([0-9]{2})/([0-9]{2})/([0-9]{4})"))
checkFormat=true;
else
checkFormat=false;
System.out.println(checkFormat);
我正在考虑拆分,然后检查它的长度,例如第一个拆分词的长度为 2,第二个拆分词的长度为 3,最后一个词的长度为 4。
但是如果输入字符串是这样的: -
AB-000-MN89
那么这里它会失败。
请帮我解决这个问题。
解决方案
正如几条评论中所述,确定您的日期是否有效的最佳方法是尝试使用 ajava.time.format.DateTimeFormatter
类型的日期对象解析它LocalDate
。
您可以支持多种模式和/或使用类中的内置模式DateTimeFormatter
:
public static void main(String[] args) {
// provide some patterns to be supported (NOTE: there are also built-in patterns!)
List<String> supportedPatterns = new ArrayList<>();
supportedPatterns.add("dd.MMM.yyyy");
supportedPatterns.add("dd MMM yyyy");
supportedPatterns.add("dd-MMM-yyyy");
supportedPatterns.add("dd/MMM/yyyy");
supportedPatterns.add("ddMMMyyyy");
// define some test input
String input = "08-Nov-2011";
// provide a variable for each, pattern and the date
String patternThatWorked = null;
LocalDate output = null;
// try to parse the input with the supported patterns
for (String pattern : supportedPatterns) {
try {
output = LocalDate.parse(input, DateTimeFormatter.ofPattern(pattern));
// until it worked (the line above this comment did not throw an Exception)
patternThatWorked = pattern; // store the pattern that "made your day" and exit the loop
break;
} catch (DateTimeParseException e) {
// no need for anything here but telling the loop to do the next try
continue;
}
}
// check if the parsing was successful (output must have a value)
if (output != null) {
System.out.println("Successfully parsed " + input
+ " to " + output.format(DateTimeFormatter.ISO_LOCAL_DATE) // BUILT-IN pattern!
+ " having used the pattern " + patternThatWorked);
}
}
这输出
Successfully parsed 08-Nov-2011 to 2011-11-08 having used the pattern dd-MMM-yyyy
推荐阅读
- javascript - 如何在 Vue.js 中过滤数组和循环 V-for
- r - `rows_update` 错误:`x` 键值不唯一
- git - 使用两个不同的分支并将它们合并?
- javascript - 每当我在 react 中保存 app.js 文件时,总是会出现错误并且出现意外令牌
- css - R闪亮的滚动侧边栏/溢出
- linux - 切换用户文件权限
- machine-learning - sklearn:SVR 无法泛化加法器功能
- node.js - 使用 Google Drive API 查看文件夹内容需要什么权限
- c++ - 如何从 C++ 的循环中追加字符串?
- python - 如何绘制带有图例的非结构化 numpy 数组?