參考博客:https://www.cnblogs.com/my-king/p/4276577.html
SimpleDateFormat.setLenient(true) : 默認值true,不嚴格解析日期,會自動計算。
SimpleDateFormat.setLenient(false):嚴格解析日期,如果日期不合格就拋異常,不會自動計算。
例子:
package com.cy.test.date; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class TestSimpleDateFormat { /** * dateFormat.setLenient 默認是true * setLenient(true),這種情況下java會把你輸入的日期進行計算,比如55個月那么就是4年以后,這時候年份就會變成03年了 * setLenient(false),這種情況下java不會把你輸入的日期進行計算,比如55個月那么就是不合法的日期了,直接異常 * @param args * @throws ParseException */ public static void main(String[] args) throws ParseException { String dob= "1/55/1999"; SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); dateFormat.setLenient(true); Date dateofbirth = dateFormat.parse(dob); System.out.println(dateofbirth); //Tue Jul 01 00:00:00 CST 2003 String dob2= "1/55/1999"; SimpleDateFormat dateFormat2 = new SimpleDateFormat("dd/MM/yyyy"); dateFormat2.setLenient(false); Date dateofbirth2 = dateFormat2.parse(dob2); //Exception in thread "main" java.text.ParseException: Unparseable date: "1/55/1999" System.out.println(dateofbirth2); } }