检查字符串是否只包含日期
Check if a string contains only date
我有一个字符串,可以包含相应格式的日期 (yyyy-MM-dd) 或日期和时间 (yyyy-MM-dd HH:mm:ss)。
我想知道哪些字符串只包含日期。
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(dateFormat.parse("2015-02-02"));
System.out.println(dateFormat.parse("2015-02-02 23:23:23"));
上述代码中,两个字符串都解析成功,只是第一个字符串的格式相同。
一旦达到所需的 format
,SimpleDateFormat
不会格式化其余的 String
。这就是为什么你的第二个字符串被解析的原因。
这个postSimpleDateFormat parse(string str) doesn't throw an exception when str = 2011/12/12aaaaaaaaa?可能对你有帮助。
同时检查 java 文档中的 DateFormat#parse
方法
public static void main(String[] args) {
String dateOnly = "2015-02-02";
String dateAndTimeOnly = "2015-02-02 23:23:23";
System.out.println("Date Only = " + validateDateFormat(dateOnly));
System.out.println("Date And time Only = " + validateDateFormat(dateAndTimeOnly));
}
public static boolean validateDateFormat(String input) {
return input.matches("([0-9]{4})-([0-9]{2})-([0-9]{2})");
}
输出
Date Only = true
Date And time Only = false
正则表达式不言自明 - 输入将由 -
分隔,第一部分([0-9]{4}
)可以包含 4 位数字,第二部分可以包含 2 位数字 [0-9]{2}
,因此第三部分.
我会使用 parse
的重载,它需要一个 ParsePosition
- 然后你可以检查位置:
import java.util.*;
import java.text.*;
public class Test {
public static void main(String[] args) throws Exception {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
System.out.println(parseFully(dateFormat, "2015-02-02"));
System.out.println(parseFully(dateFormat, "2015-02-02 23:23:23"));
}
private static Date parseFully(DateFormat format, String text)
throws ParseException {
ParsePosition position = new ParsePosition(0);
Date date = format.parse(text, position);
if (position.getIndex() == text.length()) {
return date;
}
if (date == null) {
throw new ParseException("Date could not be parsed: " + text,
position.getErrorIndex());
}
throw new ParseException("Date was parsed incompletely: " + text,
position.getIndex());
}
}
java.time
java.util
日期时间 API 及其格式 API、SimpleDateFormat
已过时且容易出错。建议完全停止使用它们并切换到 modern Date-Time API*.
解决方案使用 java.time
,现代日期时间 API:
让我们先按照您的方法来做:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String[] arr = { "2015-02-02", "2015-02-02 23:23:23" };
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd", Locale.ENGLISH);
for (String s : arr) {
System.out.println("Attempting to parse '" + s + "':");
LocalDate date = LocalDate.parse(s, dtf);
System.out.println("Parsed successfully: " + date);
}
}
}
输出:
Attempting to parse '2015-02-02':
Parsed successfully: 2015-02-02
Attempting to parse '2015-02-02 23:23:23':
Exception in thread "main" java.time.format.DateTimeParseException: Text
'2015-02-02 23:23:23' could not be parsed, unparsed text found at index 10
如您所见,java.time
API 正确抛出一个异常,通知您这个问题。 SimpleDateFormat
,另一方面,静默解析输入字符串,这导致了您发布的问题。
因此,使用现代日期时间 API,您有两个简单的选择:
- 简单地捕获异常并说第二个输入(即
2015-02-02 23:23:23
)不是指定日期模式的日期字符串。
- 使用函数
DateTimeFormatter#parse(CharSequence, ParsePosition)
并将 ParsePosition
索引设置为 0
。
下面给出了第二个选项的演示:
import java.text.ParsePosition;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String[] arr = { "2015-02-02", "2015-02-02 23:23:23" };
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd", Locale.ENGLISH);
for (String s : arr) {
ParsePosition pp = new ParsePosition(0);
LocalDate.from(dtf.parse(s, pp));
if (pp.getIndex() < s.length()) {
System.out.println("'" + s + "' is not a date string as per the specified date pattern.");
}
}
}
}
输出:
'2015-02-02 23:23:23' is not a date string as per the specified date pattern.
注: Never use SimpleDateFormat or DateTimeFormatter without a Locale.
了解有关现代日期时间 API 的更多信息
* 无论出于何种原因,如果您必须坚持Java 6 或Java 7,您可以使用ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and 。
我有一个字符串,可以包含相应格式的日期 (yyyy-MM-dd) 或日期和时间 (yyyy-MM-dd HH:mm:ss)。
我想知道哪些字符串只包含日期。
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(dateFormat.parse("2015-02-02"));
System.out.println(dateFormat.parse("2015-02-02 23:23:23"));
上述代码中,两个字符串都解析成功,只是第一个字符串的格式相同。
一旦达到所需的 format
,SimpleDateFormat
不会格式化其余的 String
。这就是为什么你的第二个字符串被解析的原因。
这个postSimpleDateFormat parse(string str) doesn't throw an exception when str = 2011/12/12aaaaaaaaa?可能对你有帮助。
同时检查 java 文档中的 DateFormat#parse
方法
public static void main(String[] args) {
String dateOnly = "2015-02-02";
String dateAndTimeOnly = "2015-02-02 23:23:23";
System.out.println("Date Only = " + validateDateFormat(dateOnly));
System.out.println("Date And time Only = " + validateDateFormat(dateAndTimeOnly));
}
public static boolean validateDateFormat(String input) {
return input.matches("([0-9]{4})-([0-9]{2})-([0-9]{2})");
}
输出
Date Only = true
Date And time Only = false
正则表达式不言自明 - 输入将由 -
分隔,第一部分([0-9]{4}
)可以包含 4 位数字,第二部分可以包含 2 位数字 [0-9]{2}
,因此第三部分.
我会使用 parse
的重载,它需要一个 ParsePosition
- 然后你可以检查位置:
import java.util.*;
import java.text.*;
public class Test {
public static void main(String[] args) throws Exception {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
System.out.println(parseFully(dateFormat, "2015-02-02"));
System.out.println(parseFully(dateFormat, "2015-02-02 23:23:23"));
}
private static Date parseFully(DateFormat format, String text)
throws ParseException {
ParsePosition position = new ParsePosition(0);
Date date = format.parse(text, position);
if (position.getIndex() == text.length()) {
return date;
}
if (date == null) {
throw new ParseException("Date could not be parsed: " + text,
position.getErrorIndex());
}
throw new ParseException("Date was parsed incompletely: " + text,
position.getIndex());
}
}
java.time
java.util
日期时间 API 及其格式 API、SimpleDateFormat
已过时且容易出错。建议完全停止使用它们并切换到 modern Date-Time API*.
解决方案使用 java.time
,现代日期时间 API:
让我们先按照您的方法来做:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String[] arr = { "2015-02-02", "2015-02-02 23:23:23" };
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd", Locale.ENGLISH);
for (String s : arr) {
System.out.println("Attempting to parse '" + s + "':");
LocalDate date = LocalDate.parse(s, dtf);
System.out.println("Parsed successfully: " + date);
}
}
}
输出:
Attempting to parse '2015-02-02':
Parsed successfully: 2015-02-02
Attempting to parse '2015-02-02 23:23:23':
Exception in thread "main" java.time.format.DateTimeParseException: Text
'2015-02-02 23:23:23' could not be parsed, unparsed text found at index 10
如您所见,java.time
API 正确抛出一个异常,通知您这个问题。 SimpleDateFormat
,另一方面,静默解析输入字符串,这导致了您发布的问题。
因此,使用现代日期时间 API,您有两个简单的选择:
- 简单地捕获异常并说第二个输入(即
2015-02-02 23:23:23
)不是指定日期模式的日期字符串。 - 使用函数
DateTimeFormatter#parse(CharSequence, ParsePosition)
并将ParsePosition
索引设置为0
。
下面给出了第二个选项的演示:
import java.text.ParsePosition;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String[] arr = { "2015-02-02", "2015-02-02 23:23:23" };
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd", Locale.ENGLISH);
for (String s : arr) {
ParsePosition pp = new ParsePosition(0);
LocalDate.from(dtf.parse(s, pp));
if (pp.getIndex() < s.length()) {
System.out.println("'" + s + "' is not a date string as per the specified date pattern.");
}
}
}
}
输出:
'2015-02-02 23:23:23' is not a date string as per the specified date pattern.
注: Never use SimpleDateFormat or DateTimeFormatter without a Locale.
了解有关现代日期时间 API 的更多信息* 无论出于何种原因,如果您必须坚持Java 6 或Java 7,您可以使用ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and