首页javalegacy_dateJava Data Type - 如何通过SimpleDateFormat解析错误与失败的输入字符串日期

Java Data Type - 如何通过SimpleDateFormat解析错误与失败的输入字符串日期

我们想知道如何通过SimpleDateFormat解析错误与失败的输入字符串日期。

public void setLenient(boolean lenient) specifies whether or not date/time parsing is to be lenient. With lenient parsing, the parser may use heuristics to interpret inputs that do not precisely match this object's format.

With strict parsing, inputs must match this object's format.

import java.text.ParseException; import java.text.SimpleDateFormat; public class Main { public static void main(String[] argv) { java.util.Date date; SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); // Lenient try { date = sdf.parse("40/02/2015"); System.out.println("Lenient date is : " + date); } catch (ParseException e) { e.printStackTrace(); } // Rigorous sdf.setLenient(false); try { date = sdf.parse("40/02/2015"); System.out.println("Rigorous date (won't be printed!): " + date); } catch (ParseException e) { e.printStackTrace(); } } }