[英]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"));
在上面的代碼中,兩個字符串都被成功解析,而只有第一個的格式相同。
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
正則表達式是自解釋的-輸入將被分離-
,IST部分( [0-9]{4}
可包含4位,第二部分可以包含2位[0-9]{2}
從而第三。
我會使用帶有ParsePosition
的parse
重載 - 然后你可以檢查位置:
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.util
Date-Time API 及其格式化 API SimpleDateFormat
已過時且容易出錯。 建議完全停止使用它們並切換到現代 Date-Time API * 。
使用現代日期時間 API java.time
解決方案:
讓我們首先嘗試按照您的方式進行操作:
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);
}
}
}
輸出:
嘗試解析“2015-02-02”:
解析成功:2015-02-02
試圖解析“2015-02-02 23:23:23”:
線程“main”中的異常 java.time.format.DateTimeParseException: Text
'2015-02-02 23:23:23' 無法解析,在索引 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' 不是指定日期模式的日期字符串。
注意:切勿在沒有 Locale 的情況下使用 SimpleDateFormat 或 DateTimeFormatter 。
從Trail: Date Time 中了解有關現代日期時間 API 的更多信息。
* 出於任何原因,如果您必須堅持使用 Java 6 或 Java 7,您可以使用ThreeTen-Backport,它將大部分java.time功能向后移植到 Java 6 和 7。如果您正在為 Android 項目和您的 Android API 工作級別仍然不符合 Java-8,請檢查 通過 desugaring和How to use ThreeTenABP in Android Project 可用的 Java 8+ APIs 。
一旦達到所需的format
, SimpleDateFormat
不會格式化String
的其余部分。 這就是解析第二個字符串的原因。
這篇文章SimpleDateFormat parse(string str) 在 str = 2011/12/12aaaaaaaaa 時不會拋出異常? 可能會幫助你。
還要檢查 java docs 中的DateFormat#parse
方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.